Mos*_*rtz 5 async-await reactjs
我有一个类,它执行很多API调用来填充状态,所以我在componentDidMount()生命周期挂钩中执行以下操作:
async componentDidMount() {
await this.populateQuote();
await this.populateCustomers();
await this.populateEmployees();
await this.populatePropertyTypes();
}
Run Code Online (Sandbox Code Playgroud)
而且每个功能都在获取一些数据并在状态中设置一些值,现在我的问题是,每当一个promise解析后,它都会重新呈现我想避免的页面,这有什么办法吗?
您应该Promise.all用来确保Promises阵列中的所有对象在执行操作之前得到解析
async componentDidMount(){
const calls = [call1(), call2(), call3()]
const results = await Promise.all(calls)
console.log(results[0],results[1],results[2])
}
Run Code Online (Sandbox Code Playgroud)
小智 5
用Promise.all()获取的所有数据,然后this.setState()执行仅重新渲染
async componentDidMount() {
const [quote, customers, employees, propertyTypes] = await Promise.all([
this.populateQuote(),
this.populateCustomers(),
this.populateEmployees(),
this.populatePropertyTypes()
]);
this.setState({
quote,
customers,
employees,
propertyTypes
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
112 次 |
| 最近记录: |