我有一个类 React 组件,它有一个 fetchData 方法,其中 api 被调用多次 我需要在 componentDidMount 方法中等待 fetchData 方法中的几个 API 调用完成
class ApartmentPage extends PureComponent {
//here is some code
componentDidMount() {
this.fetchData().then(() => {
setTimeout(() => { // how to do it without setTimeout
// here this.props must be updated by fetches
console.log('data1, data2, data3', this.props);
const data = {
data1: this.props?.data1 // +
data2: this.props.data2, // +
data3: this.props.data3, // +
};
sendData(data);
}, 500);
})
.catch((error) => {
console.warn('error', error);
});
}
{
const {
id,
fetchData1,
fetchData2,
fetchData3,
} = this.props;
let promisses = [];
this.fetchSomeData();
promisses.push(**this.fetchData1()**);
this.fetchSomeOtherData();
this.fetchSomeOtherData2();
fetchSomeData3({
id,
}).then(res => {
if (res.list && res.list.length) {
promisses.push(**fetchData2(id)**);
}
});
if(Cookies.get('user_name')) promisses.push(**fetchData3(id)**);
//promisses === [undefined, Promise]
return Promise.all(promisses).then(() => {
console.log(this.props, '123777');
});
}
}
我尝试添加 setTimeout 和数组承诺,但我很困惑
我通过检查我需要通过 sendData 调用解决的所有获取是否已返回 Promise 来解决了问题
例如我使 fetch 函数看起来像
fetchData1() {
const { id, name } = this.props;
return fetchApartment(id, name).then(response => {
if (response.data) {
this.setState({ data});
return Promise.resolve()
}
});
}
之前:
fetchData1() {
const { id, name } = this.props;
fetchApartment(id, name).then(response => {
if (response.data) {
this.setState({ data});
}
});
}
使用 hack 与 promisses 数组和 Promisses.all 我应该确保所有 promisses 数组元素都是 Promisses