Do I always need to return a value from a redux mi

2019-02-09 02:08发布

问题:

In the examples given in the redux docs, there always seems to be something being returned from middlewares. However, when I call next(action) and return nothing everything seems to work fine.

In the redux source it appears to be calling dispatch on the returned value of every middleware.

This leads me to believe that it provides an optional way to run dispatch after all the middlewares have run.

Can someone confirm if we must ALWAYS return a value from a middleware, and if so why?

回答1:

I actually tweeted about this just the other day.

The store.dispatch() method by default returns the action that was passed in. Since the middleware pipeline wraps around dispatch(), each middleware can alter the value being passed through the pipeline on the way in, and alter the return value being passed back.

Many middlewares rely on either being able to return a value themselves, or using the return value coming back. For example, redux-thunk returns whatever you return from your thunk function, and this is commonly used to be able to return a promise from a thunk so that you can chain dispatch(somePromiseThunk()).then( () => {}).

If a middleware calls next(action) but doesn't actually return the value from next(), it will potentially break those capabilities. The specific behavior will depend on what middleware you have set up, and how you have them ordered.

Because of this, the "correct" practice is that every Redux middleware should return next(action) by default unless it explicitly wants to change the return value behavior. That ensures the best compatibility and ability to compose middlewares together.