【问题标题】:Redux chaining asynchronous actions with redux-thunkRedux 使用 redux-thunk 链接异步操作
【发布时间】:2018-01-31 09:12:01
【问题描述】:

假设有 2 个日期选择器对象对应于开始日期和结束日期。

这些作为状态存在,因此为了设置它们,您必须调用 setStartDate 或 setEndDate,然后 reducer 会拾取并简单地设置状态。

假设我还有一个名为 getHugeListFromServer 的异步操作,带有 (REQUEST, SUCCESS, FAILURE) 并使用参数 getHugeListFromServer(startDate, endDate) 调用。

每次用户选择日期时,我都想调用 getHugeList 函数并更新列表。如果我做这样的事情,它不起作用,因为后端操作是在减速器设置日期变量之前调用的。

example_container.jsx

 class example extends React.Component {
... Methods
  onChangeStartDate (startDate) {
    this.props.setStartDate(startDate);
    this.props.getHugeListFromServer(startDate,  this.props.example.endDate);
  } 
  // similar method for endDate. 
} 

我安装了 redux thunk,但它仍然无法解决我的问题。我曾想过让 setDate 操作的 reducer 在调用后端操作之前返回一个承诺并在容器中解决它,但我敢打赌有更好的方法来解决这个问题。

有人可以帮忙吗?谢谢!

【问题讨论】:

  • 在您的 getHugeListFromServer 函数中,您可以调用 setStartDate 并执行默认功能。
  • 这与 getHugeListFromServer 的名称并不匹配。

标签: reactjs redux react-redux


【解决方案1】:

我曾想过让 setDate 操作的 reducer 在调用后端操作之前返回一个承诺并在容器中解决它,但我敢打赌有更好的方法来解决这个问题。

我认为这听起来一点都不合理。事实上,使用 redux,这可能完全没问题,而且可能是首选。

但是,如果您愿意,您可以查看组件的一些生命周期方法,例如 componentWillUpdate() - 每次您的状态即将更新时都会调用它。因此,您可以保持处理程序不变,但只需从中删除 this.props.getHugeListFromServer(...) 并将其放入 componentWillUpdate() 钩子中 - 请查看下面的文档链接以查看如何实现它的示例。

https://developmentarc.gitbooks.io/react-indepth/content/life_cycle/update/tapping_into_componentwillupdate.html

【讨论】:

  • 那么 redux-thunk 的真正目的是什么?难道它不应该为我解决所有这些异步减速器问题吗?
猜你喜欢
  • 1970-01-01
  • 2017-03-03
  • 2017-09-26
  • 2019-04-01
  • 2021-10-04
  • 2018-02-28
  • 1970-01-01
  • 1970-01-01
  • 2020-02-22
相关资源
最近更新 更多