6

项目Vue转成React hooks可能存在的问题–急需类似setState回调

 3 years ago
source link: https://www.daozhao.com/9938.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.

假设在Vue中有如下三个方法,并且初始时 this.a = ‘a’; this.b = ‘b’;

funA() {
        this.a = '1221';
        this.funB();
        return this.funC();
      },
      funB() {
        this.a = this.a + '--';
      },
      funC() {
        return this.a + this.b;
      }

不要纠结于上面具体的写法,只是作为demo演示现有项目中很可能有类似这样的写法。

上面在调用funA后在Vue里面可能会得到 1221-—b ,那么在React中,应该是会返回 ab 吧,因为setState的值是异步更新的,在class组件写法里面我们可以用回调来保证自己拿到的state的值是设置为更新后的结果,在hooks中呢,并没有此回调。 问题来了,要将上面的vue代码用React Hooks怎么实现,我们依然期望是像在vue中一样 funA() 稳定的返回 1221-—b

迁移技术栈的过程中,将vue的方法一对一改写成react方法肯定是业务风险最小的做法,一般情况下这样迁移没啥难度,还不会遗漏原有功能,但是我举例的这种场景vue中肯定有,需要怎么改成react hooks的写法实现类似的功能呢?


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK