首页 > 解决方案 > DidComponentUpdate 无限循环 React Native

问题描述

为什么 DidComponentUpdate 在无限循环中?

当用户在输入上更改文本时,我试图从 Api 获取一些数据

componentDidUpdate(prevState){
    if (prevState.userinput !== this.state.userinput){

fetch('https://'+this.region+'.api.riotgames.com/lol/summoner/v4/summoners/by-name/'+this.state.userinput+'?api_key='+this.apikey+'RGAPI-484c0156-6203-4611-b281-c3933b6ac175')
.then(respostauser => respostauser.json())
.then(json => this.setState({user : json}));
fetch('https://'+this.region+'.api.riotgames.com/lol/champion-mastery/v4/champion-masteries/by-summoner/'+this.state.user.accountId+'?api_key='+this.api_key)
.then(respostamastery => respostamastery.json())
.then(json => this.setState({usermastery : json}));
this.x ++;}

}

标签: reactjsreact-nativeecmascript-6jsx

解决方案


正如此处componentDidUpdate的反应文档中所述,在生命周期方法中设置状态必须使用一些条件检查来完成,否则您会遇到无限循环。

这是因为默认情况下,状态更新会导致componentDidUpdate调用该方法。在上面的代码段中,此生命周期方法包含无条件更新状态 ( this.setState) 的逻辑,因此是无限循环。


推荐阅读