reactjs - 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 ++;}
}
解决方案
正如此处componentDidUpdate
的反应文档中所述,在生命周期方法中设置状态必须使用一些条件检查来完成,否则您会遇到无限循环。
这是因为默认情况下,状态更新会导致componentDidUpdate
调用该方法。在上面的代码段中,此生命周期方法包含无条件更新状态 ( this.setState
) 的逻辑,因此是无限循环。
推荐阅读
- xml - 是否可以反编译由 Saxon 编译的样式表?
- windows - Jupyter笔记本无法在Windows上打开
- javascript - 如何在没有 babel 的 Windows 10 cmd 窗口中运行 ES6 semicolumnless 代码?
- c# - UI 图像选择器混淆
- amazon-web-services - AWS Honeycode:#value!在过滤列上使用 sum() 时出错
- arrays - 将 FileInputStream 转换为数组 [字节] Scala
- c++11 - 为什么调用移动赋值
- python-3.x - 如何通过与其类型不匹配的主键搜索 Django 模型而不引发错误?
- apache-spark-2.3 - 当左侧数据较大(~1B 记录)且具有幂律且右侧数据较小(但 > 2GB)时,我是否应该启用 shufflehashjoin
- git - 詹金斯管道 - 是否可以同时签出分支或标签