【问题标题】:Redux multiple dispatches asynchronouslyRedux 异步多次调度
【发布时间】:2017-07-18 11:58:46
【问题描述】:

我正在为我的网站使用 Redux,并且我想在页面加载时进行两次调度。第二次分派等待第一次分派(它进行 ajax 调用)完成,以便它可以使用来自第一次分派的数据。问题是现在第二次调度没有等待第一次调度完成,所以 this.props.allData 是空的。我该怎么做呢?我也尝试过使用 redux-thunk 和 promises 但无济于事。

componentWillMount() {

    this.props.dispatch(fetchAllData())
    this.props.dispatch(fetchData(this.props.allData, this.props.params.id))

}

这会给我一个错误说“无法读取未定义的属性'then'”

getAllData() {
  return (dispatch) => {
    return dispatch(fetchAllData()).then(()=> {
      dispatch(fetchData(this.props.allData, this.props.params.id))
    })
  }
}


componentWillMount() {
    this.props.dispatch(this.getAllData())
}

【问题讨论】:

  • 向我们展示您的尝试。 redux-thunk 可以轻松处理这些用例。
  • @StevenMercatante 好的已编辑帖子

标签: reactjs redux redux-thunk


【解决方案1】:

您在getAllData 中对dispatch 的调用次数过多。试试这样的:

getAllData() {
  return (dispatch) => {
    return fetchAllData().then((resp)=> {
      dispatch(fetchData(resp.payload, this.props.params.id))
    })
  }
}

【讨论】:

  • hmm fetchAllData 是我从另一个文件导入的操作,它说它是未定义的,抱歉我对 redux 和 redux-thunk 比较陌生
  • undefined 错误与 redux 或 redux-thunk 无关;这是您需要先解决的其他问题。
猜你喜欢
  • 1970-01-01
  • 2016-08-09
  • 2021-07-09
  • 2019-05-15
  • 2019-11-12
  • 2023-03-23
  • 2018-09-06
  • 2011-01-22
  • 2016-08-21
相关资源
最近更新 更多