首页 > 解决方案 > 基于方法链中的多个 setStates() 重新渲染组件的策略?

问题描述

在我的 componentDidMount() 中,我需要调用多个专门的方法。这些方法中的每一个都需要在方法结束时调用 setState。有没有办法以某种方式推迟 this.setState 执行组件重新渲染,直到所有方法都完成?这是一些伪代码,希望能说明我所想的一般概念:

componentDidMount(){
   this.setState.disableRerender();
   this.DoOneThing();
   this.DoSomethingElse();
   this.setState.enableRerender();
}

DoOneThing(){
   //this.setState(...)
}

DoSomethingElse(){
   //this.setState(...) 
}

标签: reactjs

解决方案


你可以用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)
  })
}

推荐阅读