【发布时间】: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 调用,它不会工作