Do I always need to return a value from a redux middleware?

僤鯓⒐⒋嵵緔 提交于 2020-01-11 00:57: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.



来源:https://stackoverflow.com/questions/45964129/do-i-always-need-to-return-a-value-from-a-redux-middleware

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!