React在componentWillMount中请求接口数据结束后再执行render
1.在getInitialState中初始化isloading,初始值false
1 getInitialState() {2 return {
3 editionid: '',
4 isloading:false
5 }
6 }
2.
解决方法:
增加一个加载状态,默认为 false,调用 componentWillMount() 时,设置为 true,当这个加载状态是 true 时,暂不渲染,当回调函数执行完毕后,设置为 false,此时再调用 render();
1 componentWillMount() {2 //获取当前请求的域名地址
3 this.setState({isLoading: true})
4 this.getShopId();
5 },
6
7
8 getShopId(){
9 this.get({url:"Api/lists/module/shops/key/dac509bd90a82719a3569291e12c24a6f1af4bac/id/8",
10 }).then((res)=> {
11 console.log("res",res)
12 if(res.error_code==0){
13 let editionid = res.result[0].editionid
14 if(editionid==1) {
15 this.handleClickVideo('', videoDataInit2[0]);
16 this.setState({videoData:videoData1,videoDataFlag:true,rongqiuPic:rongqiuWz,editionid:editionid})
17 }else if(editionid==2){
18 this.handleClickVideo('', videoDataInit[0]);
19 this.setState({videoData:videoData2,videoDataFlag:false,rongqiuPic:rongqiu,editionid:editionid})
20 }else{
21 this.handleClickVideo('', videoDataInit[0]);
22 this.setState({videoData:videoData2,videoDataFlag:false,rongqiuPic:rongqiu,editionid:editionid})
23 }
24 }
25 this.setState({isLoading: false})
26 });
27 },
3.最后对render进行处理
1 render() {2 let {isLoading} = this.state
3 if (isLoading) {
4 return <p>isLoading...</p>
5 }
6 return (
7 <div>要显示的部分</div>
8 )
9 }
以上是 React在componentWillMount中请求接口数据结束后再执行render 的全部内容, 来源链接: utcz.com/z/383892.html