在我的componentDidMount((中,我需要调用多个专用方法。这些方法中的每一个都需要在方法末尾调用setState。有没有办法以某种方式推迟this.setState执行组件重新渲染,直到所有方法都完成?这里有一些伪代码,希望能说明我心目中的的一般概念
componentDidMount(){
this.setState.disableRerender();
this.DoOneThing();
this.DoSomethingElse();
this.setState.enableRerender();
}
DoOneThing(){
//this.setState(...)
}
DoSomethingElse(){
//this.setState(...)
}
您可以使用async/await
执行您想要的操作,然后使用setState
执行以下操作:
async componentDidMount(){
const firstThing = await this.DoOneThing();
const secondThing = await this.DoSomethingElse();
this.setState({firstThing, secondThing})
}
DoOneThing(){
return new Promise((res, rej) => {
// do the first thing
res(5)
})
}
DoSomethingElse(){
return new Promise((res, rej) => {
// do the other thing
res(10)
})
}