DidComponentUpdate无限循环反应本机

时间:2019-04-24 00:25:58

标签: reactjs react-native ecmascript-6 jsx

为什么DidUpdate是无限循环的?

当用户在Input上输入changeText时,我试图从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 ++;}

}

1 个答案:

答案 0 :(得分:0)

如react docs here所述,在componentDidUpdate生命周期方法内设置状态必须使用一些条件检查来完成,否则您会遇到无限循环。

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