简体   繁体   中英

React Redux middleware's #store.dispatch(action) vs #next(action)

I'm learning about react redux middleware from the docs and want to know what he means by "the action will actually travel the whole middleware chain again?" Does that mean the store.dispatch(action) will have the final dispatch that is returned at the end of the middleware, whereas next(action) will only point to the dispatch at a certain point of the middleware function?

It does a bit of trickery to make sure that if you call store.dispatch(action) from your middleware instead of next(action), the action will actually travel the whole middleware chain again, including the current middleware. This is useful for asynchronous middleware, as we have seen previously.

In redux middleware is a function that patches dispatch function to extend functionality. And next function inside middleware is in fact just a copy of store.dispatch function.

function patchStoreToAddLogging(store) {
  let next = store.dispatch
  store.dispatch = function dispatchAndLog(action) {
    console.log('dispatching', action)
    let result = next(action)
    console.log('next state', store.getState())
    return result
  }
}

So when you return next(action) you return a result of dispatch function, with all previous middlewares in the chain applied, to the next middleware.

But when you call store.dispatch function you call a final dispatch method return from middleware chain with all middlewares applied.

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