Redux中间件设计re:返回值 [英] Redux middleware design re: return values

查看:111
本文介绍了Redux中间件设计re:返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我刚刚阅读了redux中间件,听起来很棒.有一件事是困扰我-中间件的返回值.

So I've just read up on redux middleware, and it sounds great. One thing is bugging me though - the return values of the middleware.

我了解到某些中间件实例返回了东西(即redux-promise),而我得到了其他中间件(即logging)却没有-只是返回了next(action)的结果.

I understand that some instances of middleware return stuff (i.e. redux-promise) , and I get that other middleware (i.e. logging) doesn't - and simply returns the result of next(action).

我的问题是,如果我想使用两个都返回东西的中间件,那会发生什么-当然,它们会互相破坏,而我只会得到最外面中间件的返回值.

My issue is what happens if I want to use two pieces of middleware that both return stuff - surely they will clobber each other and I will only get the outer-most middleware's return value.

express/connect中间件通过让中间件将其结果"写入reqres对象来解决此问题,但是redux的解决方案是什么?

express/connect middleware addresses this by letting middleware write its "results" to the req and res objects, but whats the solution with redux?

编辑

这是我的问题的一个更具体的例子:

Here is a more concrete example of my issue:

我有两个中间件:

  1. 中间件,可延迟3秒分派所有动作.该中间件返回一个可以调用以取消分派的函数
  2. 返回数字5的中间件,因为出于某种原因我需要数字5.

根据我链接中间件的这两个位的顺序,我的dispatch(action)的结果将是延迟取消fn或数字5.但是如何获得这两个结果?

Depending on the order I chain these two bits of middleware, the result of my dispatch(action) will either be the defer cancellation fn, or the number 5. But how do I get both of these results?

推荐答案

看看applyMiddleware上的文档.它解释说,中间件应被编写为可组合的,以便可以将其插入到中间件链中,而不必担心之前和之后应用的中间件:

Take a look at the documentation on applyMiddleware. It explains that middlewares are to be written to be composable, so that it can be plugged into the chain of middlewares without worrying about the middlewares that are applied before and after it:

中间件的关键特征是它是可组合的.多种的 中间件可以组合在一起,其中每个中间件都不需要 了解链中之前或之后的内容.

The key feature of middleware is that it is composable. Multiple middleware can be combined together, where each middleware requires no knowledge of what comes before or after it in the chain.

该文档在解释要传递给中间件的参数和预期收益方面做得非常好.

The documentation does a very good job of explaining the arguments that are to be passed into the middleware and the expected return.

https://redux.js.org/api/applyMiddleware

这篇关于Redux中间件设计re:返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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