我正在使用一个 API,想从我的 React 应用程序进行一些调用。它们是嵌套在 forEach() 中的异步调用。我得到所有的承诺,并将它们推入一个承诺数组中。然后使用 axios.all() 方法,如 axios 文档所述,但是当我将这些承诺的结果推送到 myData 数组时,我得到一个空数组。
除了 axios.all(promises) 方法,我尝试嵌套 then() 调用承诺,但这只会使一切复杂化。这是我的代码:
componentDidUpdate(nextProps, nextState) {
if (this.props.to !== nextProps.to || this.props.from !==
nextProps.from) {
let promises = [];
Axios.get(
`http://localhost:3000/api/visits?from=${this.props.from}&to=${
this.props.to
}`
).then(res => {
res.data.forEach(visit => {
promises.push(
Axios.get(`http://localhost:3000/api/clients/${visit.clientId}`
})
);
});
Axios.all(promises).then(results => {
results.forEach(res => {
const clientProps = {
name: res.data[0].name,
lastname: res.data[0].lastname,
mobile_number: res.data[0].mobile_number
};
myData.push(clientProps); // Here I am pushing the data to a global array
});
this.setState({myData})
});
});
}
}
当我运行代码时,我希望数组"myData"被从 API 调用推送的数据填充,但我得到一个空数组。有什么办法可以解决这个问题吗?
// I try to access data from this.state inside the render() method of my class component to generate a Table data with the name property.
<td>{this.state.myData[index].name}</td>
我想这个版本更方便。
componentDidUpdate(nextProps, nextState) {
if (this.props.to !== nextProps.to || this.props.from !==
nextProps.from) {
let promises = [];
Axios.get(
`http://localhost:3000/api/visits?from=${this.props.from}&to=${
this.props.to
}`
).then(res => {
return Axios.all(res.data.map(visit => {
return Axios.get(`http://localhost:3000/api/clients/${visit.clientId}`)
}))
})
.then(results => {
return results.map(res => {
return {
name: res.data[0].name,
lastname: res.data[0].lastname,
mobile_number: res.data[0].mobile_number
};
});
})
.then(clientProps => {
// then update state or dispatch an action
this.setState(() => ({myData: clientProps}));
});
}
}
getVisits(from, to) {
return Axios.get(`http://localhost:3000/api/visits?from=${from}&to=${to}`);
}
getClients(ids) {
return Axios.all(ids.map(id => Axios.get(`http://localhost:3000/api/clients/${id}`));
}
async getClientsOfVisits(from, to) {
const response = await this.getVisits(from, to);
const promises = await this.getClients(response.data.map(visit => visit.clientId)));
return promises.map(res => res.data[0]);
}
componentDidUpdate(nextProps, nextState) {
const { to, from } = this.props;
const toChanged = to !== nextProps.to;
const fromChanged = from !== nextProps.from;
if (toChanged || fromChanged) {
this.getClientsOfVisits(to, from).then(myData => {
this.setState({ myData });
})
}
}