当前位置 : 主页 > 网页制作 > React >

reactjs – React Redux源函数ensureCanMutateNextListeners?

来源:互联网 收集:自由互联 发布时间:2021-06-15
如何理解函数ensureCanMutateNextListeners? https://github.com/reactjs/redux/blob/master/src/createStore.js 发布从 Aaron Powell’s blog post here获得的相关部分 来自redux的订阅函数的示例实现 let subscriptions = [
如何理解函数ensureCanMutateNextListeners?
https://github.com/reactjs/redux/blob/master/src/createStore.js 发布从 Aaron Powell’s blog post here获得的相关部分

来自redux的订阅函数的示例实现

let subscriptions = [];
const subscribe = function (fn) {
    if (typeof fn !== 'function') {
        throw Error('The provided listener must be a function');
    }

    var subscribed = true;

    // This line is what we are interested in
    subscriptions.push(fn);

    return function () {
        if (!subscribed) {
            return;
        }

        var index = subscriptions.indexOf(fn);
        subscriptions.splice(index, 1);
        subscribed = false;
    };
};

对于每次执行的调度,我们必须通知每个订户.

来自博客

Now one thing you might want to add to the subscribe function is mutation hold on the subscribers collection. The reason for this that you want the collection of listeners shouldn’t change while a dispatch is running.

继续 …

So here we have a function ensureCanMutateNextListeners that, when invoked, checks if the two arrays are the same array reference, if they are, use slice to clone currentSubscriptions so that when we modify the nextSubscriptions array (adding or removing a listener) it won’t impact any currently running dispatch pipeline. The goal here is to ensure that the listeners that are used by dispatch are a point in time, for when the dispatch started.

网友评论