【问题标题】:DidComponentUpdate Infinite Loop React NativeDidComponentUpdate 无限循环 React Native
【发布时间】:2019-09-13 05:19:17
【问题描述】:

为什么 DidComponentUpdate 处于无限循环中?

当用户在 Input 上更改文本时,我试图从 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 ++;}

}

【问题讨论】:

    标签: reactjs react-native ecmascript-6 jsx


    【解决方案1】:

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

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

    【讨论】:

    • 我正在使用 if (prevState.userinput !== this.state.userinput) 已经在文档中说过,还不够吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-09-30
    • 2020-02-21
    • 2018-05-08
    • 1970-01-01
    • 2020-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多