添加componentDidUpdate时无法对已卸载的组件执行React状态更新

时间:2020-03-12 20:05:56

标签: javascript reactjs

因此,一开始我的问题是,从另一个页面(AddAlbum)重定向时,我的组件(Feed)未使用新数据(状态)更新页面。要解决此问题,我必须将componentDidUpdate()添加到我的组件(Feed)中,以将componentDidUpdate()中的状态设置为由Node JS API通过AddAlbum创建的数据。它的确呈现了我的新数据,但是出现了这个错误: Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.

这是我来自Feed的代码:

componentDidMount() {
  console.log('COMPONENT HAS MOUNTED');
  let album = this.state.album;
  fetch(`http://localhost:8000/albums`)
    .then((response) =>
      response.json())
    .then((data) => {
          this.setState({ album : data });
     }).catch((error) => {
            console.log("Error " + error)
          })

  }

componentDidUpdate() {
   fetch(`http://localhost:8000/albums`)
    .then((response) =>
      response.json())
    .then((data) => {
          this.setState({ album : data });
     }).catch((error) => {
            console.log("Error " + error)
          })

}

2 个答案:

答案 0 :(得分:0)

您可以使用isMounted React模式来避免内存泄漏。

    constructor(props) {
super(props);

this._isMounted = false; }

componentDidMount() {
   this._isMounted = true;
   this._isMounted && fetch(`http://localhost:8000/albums`)
.then((response) =>
  response.json())
.then((data) => {
      this.setState({ album : data });
 }).catch((error) => {
        console.log("Error " + error)
      })
}

componentDidUpdate() {
this._isMounted && fetch(`http://localhost:8000/albums`)
.then((response) =>
  response.json())
.then((data) => {
      this.setState({ album : data });
 }).catch((error) => {
        console.log("Error " + error)
      })

}

和您的componentWillUnmount

    componentWillUnmount() {
    this._isMounted = false;
     }

详细了解此reactjs.org/blog/ismounted-antipattern.html

答案 1 :(得分:0)

我认为最好的做法是听警告,而不是尝试更新已卸载组件的状态。

  • 您可以将album var置于父组件的状态,并在Feed组件中作为prop接收数据。
  • 另一种方法是使用商店管理器(例如reduxmobxcontext),然后再次将album变量放入{{1} },并在store中作为道具接收。