如何在ReactJS中完成http请求后才进行渲染

Ren*_*ier 6 javascript reactjs

我只需要在完成componentDidMount函数的请求后调用我的组件的render函数.

componentDidMount(){    
    let ctx = this;
    ApiService.get('/busca/empresa/pagina').then(function(response){
      if(response.data.empresa){
        ctx.setState({company:response.data.empresa});
        ctx.getProducts();
        ctx.verifyAuthentication();
      }
    }, function(error){
       Notification.error('HTTP Status: ' + error.response.status + ' - ' + error.response.data.mensagem);
    });
}
Run Code Online (Sandbox Code Playgroud)

问题是当打开页面时,在componentDidMount完成之前调用render函数.始终从else条件(renderNotValidateCompany)返回函数并在更新this.state.company后返回renderValidateCompany.

render(){
    if(this.state.company){
      return this.renderValidateCompany();
    }else{
      return this.renderNotValidateCompany();
    }
}
Run Code Online (Sandbox Code Playgroud)

是否有可能只在componentDidMount在react中完成时才调用渲染?

谢谢!

Jan*_*łek 2

就像我在评论中所说,将请求状态存储在状态中并根据它进行渲染:

this.state = {
  company:null,
  requestCompleted:false,
}
Run Code Online (Sandbox Code Playgroud)

在渲染方法中:

render(){
 if(this.state.requestCompleted && this.state.company){
    return this.renderValidateCompany();
  }
 else if (this.state.requestCompleted){
    return this.renderNotValidateCompany();
  }
 else {
  return <LoadingGif />
  {/*or return null*/}
 }
}
Run Code Online (Sandbox Code Playgroud)

当然更新 Promise 中的请求状态。