如何一个接一个地分派多个动作 [英] How to dispatch multiple actions one after another

查看:39
本文介绍了如何一个接一个地分派多个动作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 react/redux 应用程序中,我经常想要一个接一个地分派多个动作.

In my react / redux application I often want to dispatch multiple actions after another.

以下示例:成功登录后,我想存储用户数据,之后我想启动另一个异步操作,从服务器加载应用程序配置.

Given the following example: After a successful login I want to store the user data and after that I want to initiate another async action that loads application configuration from the server.

我知道我可以使用 redux-thunk 来构建这样的动作创建器

I know that I can use redux-thunkto build an action creator like this

function loginRequestSuccess(data) {
  return function(dispatch) {
    dispatch(saveUserData(data.user))
    dispatch(loadConfig())
  }
}

所以我的问题是:

  1. 当第一个 dispatch 返回时,所有侦听该操作的 reducer 是否已经更改了状态?我想知道这两个调度调用是否严格按顺序运行.
  2. 这种方法是否被视为调度多个操作的最佳实践?如果没有,您有什么替代建议?
  1. When the first dispatchreturns, is the state already changed by all reducers listening for that action? I'm wondering if the two dispatch calls are run strictly sequential.
  2. Is this approach considered best practice for dispatching multiple actions? If not, what would you suggest alternatively?

感谢您的帮助!

推荐答案

是的 redux-thunk 允许你按照你说的做,是的,这是调度多个操作的最佳实践(我更喜欢一个替代方案,因为这很简单).状态确实会在您调度时(在它返回时)立即更新,这就是为什么给您一个函数来检索 thunk 中的状态,而不是简单地引用状态.通过这种方式,您可以通过一次调度更改状态,然后调用 getState() 以获取对新状态的引用,以便在需要时读取.

Yes redux-thunk allows you to do as you say, and yes it is a best practice for dispatching multiple actions (one that I prefer over the alternatives because of it's simplicity). The state is indeed updated as soon as you dispatch (by the time it returns), which is why you are given a function to retrieve the state in a thunk, instead of simply a reference to the state. In that way you can alter the state with one dispatch, and then call getState() to get a reference to the new state to read from if you need to.

这篇关于如何一个接一个地分派多个动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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