You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
functionrunReactionsHelper(){globalState.isRunningReactions=trueconstallReactions=globalState.pendingReactionsletiterations=0// 遍历所有globalState.pendingReactions中的reaction,并执行每个对象的runReactionwhile(allReactions.length>0){if(++iterations===MAX_REACTION_ITERATIONS){console.error(`Reaction doesn't converge to a stable state after ${MAX_REACTION_ITERATIONS} iterations.`+` Probably there is a cycle in the reactive function: ${allReactions[0]}`)allReactions.splice(0)// clear reactions}letremainingReactions=allReactions.splice(0)for(leti=0,l=remainingReactions.length;i<l;i++)remainingReactions[i].runReaction()}globalState.isRunningReactions=false}
最后,我们也可以看到mobx抽离Reaction这一层,设计的很巧妙,不仅抽离了依赖收集的逻辑,管理全局的依赖管理,也抽离了不同依赖管理阶段side effect,在初始化依赖收集的时候可以设置track get 方法,在依赖更新的时候也可以将Reaction用作他处,比如React,进行组件的更新。
The text was updated successfully, but these errors were encountered:
先看下面的代码:
修改test的值,会触发log函数自动执行。相当于传入autorun的方法,会自动收集依赖到的 observable值的变化。个人猜测autorun函数的工作方式是这样的
下面来简单看一下autorun源码 (5.15.4)
再来看看runReactions,runReactions是依赖收集启动方法
runReactionsHelper:
runReaction关键就是触发onInvalidate参数函数, 也就是用track包裹的view函数(autorun的传入函数)
终于到trackDerivedFunction了,trackDerivedFunction就是最终调用autorun的传入函数的方法。至此就完成了触发observable属性的get方法。后面就是监听observable属性的get方法的调用, 最终完成依赖收集。例如在mobx ObservableValue类中有一个get方法,这个方法就是trap了observable属性的get方法:
至此完成了依赖收集。
下面来简单的说一下obserable属性的set方法,触发set方法,如果值改变,mobx会通知此obserable属性的依赖:
最后,我们也可以看到mobx抽离Reaction这一层,设计的很巧妙,不仅抽离了依赖收集的逻辑,管理全局的依赖管理,也抽离了不同依赖管理阶段side effect,在初始化依赖收集的时候可以设置track get 方法,在依赖更新的时候也可以将Reaction用作他处,比如React,进行组件的更新。
The text was updated successfully, but these errors were encountered: