我只需要在完成对 componentDidMount 函数的请求后调用我的组件的渲染函数。
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);
});
}
问题在于,当打开页面时,渲染函数在 componentDidMount 完成之前被调用。始终从 else 条件 (renderNotValidateCompany) 返回函数并在更新 this.state.company 后返回 renderValidateCompany。
render(){
if(this.state.company){
return this.renderValidateCompany();
}else{
return this.renderNotValidateCompany();
}
}
有没有可能是react中componentDidMount完成才调用rendering?
谢谢!
最佳答案
就像我在评论中所说的那样,将请求状态存储在状态中并基于它进行渲染:
this.state = {
company:null,
requestCompleted:false,
}
在渲染方法中:
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*/}
}
}
当然会在 Promise 中更新请求状态。
关于javascript - 如何仅在 ReactJS 中完成 http 请求后才进行渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45808247/