3

vue迁移react使用useReducer hooks还想支持回调?

 3 years ago
source link: https://www.daozhao.com/9947.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

vue迁移react使用useReducer hooks还想支持回调?

如果您发现本文排版有问题,可以先点击下面的链接切换至老版进行查看!!!

vue迁移react使用useReducer hooks还想支持回调?

鉴于目前有个任务是把手上的vue项目迁移到react,为了尽可能的降低期间造成的功能缺陷,很自然的就会想到使用一个方法一个方法的迁移,有的场景在vue中很自然,在react中,尤其是在使用react hooks时,有的过程就不好弄,我就毕竟苦于在react hooks中没有class组件里面的setState的回调函数,导致后面的取值拿不到最新的state。 比如下面的例子。

In vue

export default {
  name: 'VueComponent',
  data() {
    return {
      a: 'a',
      b: 'b',
    };
  },
  mounted() {
    console.log('result', this.funA()); // 1221--b
  },
  methods: {
    funA() {
      this.a = '1221';
      this.funB();
      return this.funC();
    },
    funB() {
      this.a = this.a + '--';
    },
    funC() {
      return this.a + this.b;
    }
  }
};

To react

import React, { useReducer } from 'react';
const [state, dispatch] = useReducer((state, action) => {
    switch(action.type) {
        case 'clear':
     retrun {
        a: '',
        b: '',
     }
     case 'upate':

    }
    return {
        ...state,
        ...payload,
    };
}, {
    a: 'a',
    b: 'b',
});

function funA() {
    dispatch({
        a: '1221',
    });
    funB();
    return funC();
}

function funB() {
    dispatch({
        a: state.a + '--',
    });
}

function funC() {
    return state.a + state.b;
}

useEffect(() => {
    console.log('useEffect -> ', funA()); // "ab", not the expected "1221--b" like in vue
}, []);

为此自己做了一个简单的npm包,报名就是react-hooks-like-vue, 用了这个包就会是这样,比较解决原来vue中的写法。

import { useDispatch } from 'reac-hooks-like-vue';
  const [state, dispatch] = useDispatch({
    a: 'a',
    b: 'b',
  });

function funA() {
    dispatch({
        a: '1221',
    });
    funB();
    return funC();
}

function funB() {
    dispatch({
        a: state.a + '--',
    });
}

function funC() {
    return state.a + state.b;
}

useEffect(() => {
    console.log('useEffect -> ', funA()); // "1221--b", as expected, like in vue
}, []);
更新时间:2020-12-29 11:47

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK