reactjs - react ComponentDidUpdate 上的无限循环
问题描述
我有一个名为 Event 的模型,在更新 Event 之后,当我尝试使用 componentDidUpdate 更新对视图的更改时,它会永远循环(无限循环)。我已经搜索并看到有同样问题的人,但我似乎无法让它工作。
这是我在组件内的EventComments
componentDidUpdate
componentDidUpdate() {
axios
.get(
"http://localhost:9000/events/" +
this.props.match.params.id +
"/eventcomments"
)
.then((response) => {
this.setState({ event: response.data });
this.setState({ eventcomments: response.data.eventcomments });
})
.catch(function (error) {
console.log(error);
});
}
请问我应该怎么做才能让这个无限循环停止?
解决方案
您需要将事件包装在条件中。来自文档的参考:
componentDidUpdate(prevProps) {
// Typical usage (don't forget to compare props):
if (this.props.userID !== prevProps.userID) {
this.fetchData(this.props.userID);
}
}
你的例子:
componentDidUpdate(prevProps) {
if(prevProps.id !== this.props.match.params.id){
axios
.get(
"http://localhost:9000/events/" +
this.props.match.params.id +
"/eventcomments"
)
.then((response) => {
this.setState({ event: response.data });
this.setState({ eventcomments: response.data.eventcomments });
})
.catch(function (error) {
console.log(error);
});
}
}
推荐阅读
- android - FirebaseRecyclerAdapter 的问题,在删除数据时在空对象引用上
- sql - Oracle 查询到 PostgreSQL 的转换
- vps - 在 vps 上找不到 phpmyadmin 404
- tensorflow - tensorflow-gpu 错误:由于 EnvironmentError 无法安装软件包:[Errno 2] 没有这样的文件或目录:
- javascript - 使用 JavaScript 生成序列号
- python - 是否可以使用 Fiona 读取 GML 或 KML 文件?
- javascript - 将变量从控制器传递到无脂肪框架中的 javascript 函数
- python - 无法在 Google Colab 中使用 bash 运行 Starspace
- python - 我可以使用哪个 numpy 命令多次减去不同维度的向量?
- xamarin.forms - 将 SFDataGrid 的列绑定到 Xamarin Forms 中的 ViewModel 属性