zoukankan      html  css  js  c++  java
  • react生命周期函数使用箭头函数,导致mobx-react问题

    最近新人加入了项目,遇到了一个很奇怪的问题。mobx observable 属性,onChange的时候就是页面不会刷新。

    试来试去,就是不知道什么原因,后来其他同事查到是因为componentWillMount写成了箭头函数,真的是防不胜防啊。

    错误代码如下,componentWillMount的箭头函数去掉就妥妥的对的

    whyRun函数运行的结果如下,显示的意思是没有在收集依赖的函数中运行

      whyRun() can only be used if a derivation is active, or by passing an computed value / reaction explicitly.

      If you invoked whyRun from inside a computation;

      the computation is currently suspended but re-evaluating because somebody requested its value.

    但是为什么呢??那只能看看mobx-react源代码了,下面observer方法的截图,删除了几行,通过mixinLifecycleEvents对react组件的生命周期函数进行了扩展

    下面是patch方法的实现,是不是有种切面编程,函数after,before的影子

    具体"componentWillMount", "componentDidMount", "componentWillUnmount", "componentDidUpdate"方法进行了哪些扩展,不是今天的重点(我也不是很清楚)。

    componentWillMount的扩展比较重要,

    主要做了下面几件事

      props,state 通过 Atom 对象封装 

      定义方法initialRender,创建 Reaction对象(当可监听依赖变化的时候,触发组件forceUpdate),跟踪收集 原render函数 里面的依赖

      用initialRender覆盖原render函数

    当组件componentWillMount函数,使用了箭头函数,就会在组件 constructor 方法中,bind this并直接覆盖方法,使得mobx-react都白干了,

    所以whyRun也会提示没有在收集跟踪方法中运行了。

    在代码中箭头函数还是不能滥用啊~~

  • 相关阅读:
    python 杂谈
    python: list转字符串
    dataframe
    time模块
    python 调试器
    BAT机器学习面试1000题系列(41-45题)
    join()函数
    value_counts()
    模型评估
    04flask_scripts使用
  • 原文地址:https://www.cnblogs.com/legu/p/8289813.html
Copyright © 2011-2022 走看看