Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

redux 中间件及小点 #2

Open
jyzwf opened this issue Jan 28, 2018 · 0 comments
Open

redux 中间件及小点 #2

jyzwf opened this issue Jan 28, 2018 · 0 comments

Comments

@jyzwf
Copy link
Owner

jyzwf commented Jan 28, 2018

关于中间件流程,直接看下面一幅图就大致可以理解了
middle2

接下来是一些思考或者说是值得学习的地方

1. createStore.js里面的一个函数 --> ensureCanMutateNextListeners

function ensureCanMutateNextListeners() {
        // 判断 nextListeners 和 currentListeners 是同一个引用
        if (nextListeners === currentListeners) {
            // 通过数组的 slice 方法,复制出一个 listeners ,赋值给 nextListeners
            nextListeners = currentListeners.slice()
        }
    }

为什么要出现这个函数呢??

这部分代码上面有几行英文注释大致讲述了原因,
当我们 dispatch的时候,这时会先执行如下步骤:

        const listeners = (currentListeners = nextListeners)

就是先将 nextListener 赋值给 currentListener 在赋值给 listener ,接着就是执行之前 subscribe 里面注册的监听器了,我们可以想象如下场景:

let unSubscribe1 = store.subscribe(() => {
    let unSubscribe2 = store.subscribe(()=>{})
    // 或者取消之前的一个订阅
})

在执行监听器的时候,里面又进行了订阅,那么,现在假设已经执行了前面订阅的监听函数,现在又取消了,或者又添加了新的订阅监听器,这样子就会出现不确定性和不知名的错误。所以,redux 统一将后面当前 listener 函数执行里面又订阅的 listener 安排到 下一轮 执行。

我们可以分析,当 listener 函数里面又进行 subscribe 时,会调用 ensureCanMutateNextListeners,这时候,currentListeners = nextListeners,会执行 ifnextListeners 将拷贝 currentListeners 的副本,subscribe 订阅的 listener 函数就会被放进 nextListeners,以便下一轮的执行,这样就不会影响到 currentListeners ,也就是本轮执行的 listeners 集合。避免了错误

@jyzwf jyzwf changed the title redux 中间件 redux 中间件及小点 Jan 30, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant