简体   繁体   English

在redux中,当编写请求调度时,“ next”和“ store.dispatch”之间有什么区别?

[英]In redux when writing thunks for dispatch, what's the difference between “next” and “store.dispatch”?

In the video lesson: https://egghead.io/lessons/javascript-redux-dispatching-actions-asynchronously-with-thunks we learn to write our own thunks so that we can have asynchronous & multiple calls of dispatch in an action creator. 在视频课程中: https : //egghead.io/lessons/javascript-redux-dispatching-actions-asynchronously-with-thunks我们学习编写自己的thunk,以便我们可以在动作创建者中进行异步和多个调用调度。 I understand this for the most part. 我大部分都了解这一点。

However, I am confused at why we used store.dispatch instead of next in the thunk: 但是,我对为什么我们在store.dispatch使用store.dispatch而不是next感到困惑:

const thunk = (store) => (next) => (action) =>
  typeof action === 'function' ?
    action(store.dispatch) :
    next(action);

Why would one use next versus store.dispatch and vice versa? 为什么要使用next而不是store.dispatch ,反之亦然? I understand that next advances to the next middleware but if the next middleware eventually also calls dispatch, why would I use store.dispatch over next ? 我知道next前进到下一个中​​间件,但是如果下一个中间件最终也调用了dispatch,我为什么要在next使用store.dispatch

As you've already pointed out, next only calls the next middleware in the chain. 正如您已经指出的, next仅调用链中的下一个中间件。 Although it does eventually call the original dispatch function, it isn't appropriate to use it when you want to traverse the whole chain again. 尽管它最终会调用原始的调度函数,但是当您想再次遍历整个链时,不宜使用它。 In the case of thunks, you want to traverse the whole chain. 如果是重音,则要遍历整个链。

So, if you're creating a middleware where you want to do some work and then continue down the chain, use next . 因此,如果您要创建一个中间件来完成一些工作,然后继续进行next工作,请使用next For example, the logger does this: it logs the action, calls next , and then logs the resulting state. 例如,记录器执行此操作:它记录操作,调用next ,然后记录结果状态。 To return a callback that will traverse the whole chain, return store.dispatch . 要返回遍历整个链的回调,请返回store.dispatch It seems unlikely that you would want to return next from a middleware, since you would probably assume that you don't know which middlewares come before and after the current one, so the outcome of calling it outside of the middleware chain is unpredictable. 您似乎不太可能想要从中间件返回next一个,因为您可能会假设您不知道哪个中间件在当前中间件之前和之后出现,因此在中间件链之外调用它的结果是不可预测的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM