简体   繁体   中英

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. I understand this for the most part.

However, I am confused at why we used store.dispatch instead of next in the thunk:

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

Why would one use next versus store.dispatch and vice versa? 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 ?

As you've already pointed out, next only calls the next middleware in the chain. 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 . For example, the logger does this: it logs the action, calls next , and then logs the resulting state. To return a callback that will traverse the whole chain, return 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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