最近新人加入了项目,遇到了一个很奇怪的问题.mobx observable 属性,onChange 的时候就是页面不会刷新.
试来试去,就是不知道什么原因,后来其他同事查到是因为 componentWillMount 写成了箭头函数,真的是防不胜防啊.
错误代码如下,componentWillMount 的箭头函数去掉就妥妥的对的
whyRun 函数运行的结果如下,显示的意思是没有在收集依赖的函数中运行
但是为什么呢??那只能看看 mobx-react 源代码了,下面 observer 方法的截图,删除了几行,通过 mixinLifecycleEvents 对 react 组件的生命周期函数进行了扩展
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.
下面是 patch 方法的实现,是不是有种切面编程,函数 after,before 的影子
具体 "componentWillMount", "componentDidMount", "componentWillUnmount", "componentDidUpdate" 方法进行了哪些扩展,不是今天的重点(我也不是很清楚).
componentWillMount 的扩展比较重要,
主要做了下面几件事
props,state 通过 Atom 对象封装
定义方法 initialRender,创建 Reaction 对象(当可监听依赖变化的时候,触发组件 forceUpdate),跟踪收集 原 render 函数 里面的依赖
用 initialRender 覆盖原 render 函数
当组件 componentWillMount 函数,使用了箭头函数,就会在组件 constructor 方法中,bind this 并直接覆盖方法,使得 mobx-react 都白干了,
所以 whyRun 也会提示没有在收集跟踪方法中运行了.
在代码中箭头函数还是不能滥用啊~~
来源: http://www.bubuko.com/infodetail-2462744.html