首页 > 解决方案 > react ComponentDidUpdate 上的无限循环

问题描述

我有一个名为 Event 的模型,在更新 Event 之后,当我尝试使用 componentDidUpdate 更新对视图的更改时,它会永远循环(无限循环)。我已经搜索并看到有同样问题的人,但我似乎无法让它工作。

这是我在组件内的EventCommentscomponentDidUpdate

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);
  });
}

请问我应该怎么做才能让这个无限循环停止?

标签: reactjs

解决方案


您需要将事件包装在条件中。来自文档的参考:

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);
  });
}
}

推荐阅读