【问题标题】:Axios.all in componentWillReceiveProps not calledcomponentWillReceiveProps 中的 axios.all 未调用
【发布时间】:2017-08-30 12:30:22
【问题描述】:

使用 React 和 Redux,我需要等待我的所有操作都完成才能更新组件状态。阅读 Axios 文档时,我发现 axios.all 可以收集我的所有操作并等待所有操作都得到解决(基本上我调用 API n 次以获取有关 n 个项目的信息)。 问题是 axios.all 的 .then 函数中的 console.log 根本不返回任何内容,但动作被正确调度。

if (this.props.evaluation && this.props.evaluation.topics) {
  var promises = []

  var array = this.props.evaluation.topics;
  var selectedArray = []
  for (var i = 0; i < array.length; i++) {
    promises.push(this.props.fetchTopic(array[i]))
  }

  axios.all(promises).then(function(results) {
    results.forEach(function(response) {
      console.log('///////////////////////');
      console.log(response.value);
      console.log('///////////////////////');
    })
  });
}

编辑:这是我的 fetchTopic 代码

在我的组件中:

const mapDispatchToProps = (dispatch) => ({
  fetchTopic: (id) => dispatch(fetchTopic(id)),
})

在我的 actions.js 中

export const fetchTopic = (id) => ({
  type: "FETCH_TOPIC",
  payload: axios.get(process.env.SERVICE_URL + '/topic/' + id, { headers: { 'Authorization': 'JWT ' + sessionStorage.jwt }})
})

【问题讨论】:

  • 添加fetchTopic 代码。确保它返回一个承诺。
  • Actions 创建者必须返回普通的 javascript 对象,你的是在有效负载中返回一个 axios 调用,它不会工作

标签: reactjs redux axios


【解决方案1】:

改变这个

export const fetchTopic = (id) => ({
  type: "FETCH_TOPIC",
  payload: axios.get(process.env.SERVICE_URL + '/topic/' + id, { headers: { 'Authorization': 'JWT ' + sessionStorage.jwt }})
})

到这里

   export const fetchTopic = (id, cb) => {
     axios.get(process.env.SERVICE_URL + '/topic/' + id, { headers: { 'Authorization': 'JWT ' + sessionStorage.jwt }})
     .then((response) => {
       if (cb) cb({ type: "FETCH_TOPIC", payload:response })
     });
    }

然后运行

for (var i = 0; i < array.length; i++) {
  this.props.fetchTopic(array[i], (result) => {
    // get the result here
  })
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-03
    • 2017-03-12
    • 2018-08-16
    • 1970-01-01
    • 2018-08-16
    • 2019-10-26
    • 2022-01-22
    • 2016-11-29
    相关资源
    最近更新 更多