我是否总是需要从 redux 中间件返回一个值? [英] Do I always need to return a value from a redux middleware?

查看:49
本文介绍了我是否总是需要从 redux 中间件返回一个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

redux 文档 中给出的示例中,有似乎总是从中间件返回的东西.但是,当我调用 next(action) 并没有返回任何内容时,一切似乎都正常.

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.

redux 源 中,它似乎是对每个中间件的返回值调用 dispatch.

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

这让我相信它提供了一种在所有中间件运行后运行 dispatch 的可选方式.

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?

推荐答案

我实际上在推特上讨论了这个问题一天.

store.dispatch() 方法默认返回传入的 action.由于中间件管道环绕 dispatch(),每个中间件都可以改变值在进入的途中通过管道,并改变被传回的返回值.

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.

许多中间件依赖于能够自己返回一个值,或者使用返回的返回值.例如,redux-thunk 返回您从 thunk 函数返回的任何内容,这通常用于能够从 thunk 返回承诺,以便您可以链接 dispatch(somePromiseThunk()).then( () => {}).

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( () => {}).

如果中间件调用 next(action) 但实际上并未从 next() 返回值,则它可能会破坏这些功能.具体行为取决于您设置的中间件以及订购方式.

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.

因此,正确"的做法是每个 Redux 中间件应该 return next(action) 默认情况下,除非它明确想要更改 return价值行为.这确保了将中间件组合在一起的最佳兼容性和能力.

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.

这篇关于我是否总是需要从 redux 中间件返回一个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆