简体   繁体   English

使用redux时如何在componentWillMount中加载数据

[英]How to load data in componentWillMount when using redux

I'm have trouble figuring out how to structure my code with redux. 我很难弄清楚如何用redux构建我的代码。 Here's the high level flow that I'm looking at: 这是我正在关注的高级流程:

  1. An action execute successfully, and triggers history.push('/something') 一个动作成功执行,并触发history.push('/something')
  2. That leads a new component Something to be loaded 这导致了一个新的组件Something to loaded
  3. In Something.componentWillMount() , I want to fetch some data for the component, so I call this.props.loadSomething() , which is another action Something.componentWillMount() ,我想获取组件的一些数据,所以我调用this.props.loadSomething() ,这是另一个动作

Step (3) is the problem. 步骤(3)是问题所在。 Since the history.push() call is in an action, redux doesn't let me call this.props.loadSomething() , since that would be calling an action within an action. 由于history.push()调用是在一个动作中,因此redux不允许我调用this.props.loadSomething() ,因为那将调用一个动作中的动作。

What is the proper way to handle this? 处理这个问题的正确方法是什么? I feel like this must be a very common problem, so there should be a standard approach for it. 我觉得这一定是一个非常普遍的问题,所以应该有一个标准的方法。

What you're looking at is indeed a common scenario. 您所看到的确实是一种常见情况。 The easy way around the problem is the use of a thunk. 解决问题的简单方法是使用thunk。

It is basically built so that you can dispatch multiple actions simultaneously and they can even be asynchronous. 它基本上是构建的,因此您可以同时分派多个动作,甚至可以是异步的。

You can find relevant documentation here . 您可以在此处找到相关文档。

Sample usage in an app, an action creator: 应用中的示例用法,操作创建者:

export function doSomething(someParam, someOtherParam) {
  return dispatch => {
    dispatch(someOtherActionCreator(someParam));
    dispatch(loadMyDataActionCreator(someParam, someOtherParam));
  };
}

You could possibly only redirect once you've loaded the data. 您可能只有在加载数据后才能重定向。 You can also do that with thunks. 你也可以用thunk做到这一点。

export function fetchMeStuffNRedirect(params) {
  return dispatch => {
    return dispatch(loadSomeStuffThatReturnsPromise())
    .then(result => dispatch(doSomethingWithResult(result))
    .catch(error => dispatch(awSnapActionCreator(error));
  };
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM