我有一个组件,它依赖于呈现内容之前要异步检索的数据。如果数据尚不可用,则render函数将返回一个Loader组件:
if (this.state.loading) {
return <Loader />;
}
调用返回数据后,加载状态设置为false:
componentDidMount() {
ExternalComponent.fetchData().then(response => {
this.setState({
loading: false,
data: response
});
});
}
这可以正常工作,但是如果我想并行添加另一个异步获取调用怎么办?在将“加载”状态设置为false之前,我该如何正确地等待两者完成?
使用Promise.all:
componentDidMount() {
const fetchData1 = ExternalComponent.fetchData()
const fetchData2 = AnotherExternalComponent.fetchData()
Promise.all([ fetchData1, fetchData2 ]).then((responses) => {
this.setState({
loading: false,
data: responses[0]
});
});
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句