最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Do I always need to return a value from a redux middleware? - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question asked Aug 30, 2017 at 15:16 Dan Green-LeipcigerDan Green-Leipciger 3,9321 gold badge21 silver badges32 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 26

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.

发布评论

评论列表(0)

  1. 暂无评论