javascript - 我需要在中间件中使用 `next` 或 `store.dispatch`

标签 javascript redux

我正在构建我的异步中间件,我想从中分派(dispatch)多个操作。目前的情况如下:

const [ requestType, successType, failureType ] = types;
next({type: requestType});

return call().then(
    result => {
        return next({
            result,
            type: successType
        })
    },
    error =>  {
        // I want to dispath the `sendNotification()` action here
        // to add item to notifications center
        // should I use `next` or `store.dispath`?

        //this way?
        store.dispath(failedNotification);
        //or this way?
        next(failedNotification);

        return next({
            type: failureType,
            error: error.message || 'Something bad happened',
            errorType: error.errorType
        })
    }
)

我的问题在上面代码的这些注释中:

      // I want to dispath the `sendNotification()` action here
      // to add item to notifications center
      // should I use `next` or `store.dispath`?

我问的原因是因为根据我对 hereapplyMiddleware 实现细节的理解, next() 将通过剩余的中间件链传递一个操作,而 store.dispatch 将遍历整个中间件链,包括当前的中间件。

最佳答案

如果您使用store.dispatch(),调度将再次触发您的中间件并再次调用call()。有时它可能会导致无限循环,因此调用 next() 在这里看起来是一个更好的选择。

关于javascript - 我需要在中间件中使用 `next` 或 `store.dispatch`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34836302/

相关文章:

javascript - 如何为 Jekyll 页面加载外部脚本?

javascript - 从回调中调用对象的私有(private)方法

javascript - 如何将一个对象的值复制到另一个对象的键中?

javascript - 在 redux 中使用 axios 的正确方法

javascript - 无法在未登录的情况下重定向到重置密码链接

javascript - Backbone.js 突出显示页面上有大量数据已损坏

javascript - 如何使用 JQuery 从单击的元素中获取信息?

javascript - 将普通函数连接到 Redux 的 mapDispatchToProps

javascript - 在 Redux reducer 中取消将数据移至数组

reactjs - 管理模块内多个 reducer 的模式 [Redux]