What's the difference between dispatch and nex

2019-02-01 01:07发布

问题:

What's the difference between dispatch and next in Redux middleware?

export default function sampleMiddleware(store) {
  return next => action => {
   store.dispatch(action)
   next(action)
  }
}

回答1:

Dispatch initiates new action and it's go through full chain of middlewares.

Next – send current action into next middleware in chain.



回答2:

createStore(reducer,
 applyMiddleware(
 middlewareA,
 middlewareB,
 middlewareC
 )
);

Calling next(action) within middlewareB will cause the action to be passed to middlewareC and then the reducer. Calling dispatch(action) within middlewareB will cause the action to be passed to middlewareA, then middlewareB, then middlewareC, and finally to the reducer, returning the execution back to middlewareB. Calling dispatch() multiple times is a common and valid practice. next() can also be called more than once, but this is not recommended as any action passed to next() will skip the middleware before the current one (for example, potentially skipping the logging middleware).



标签: redux