警告关于UnmountedReact组件的更新

时间:2018-01-17 05:54:26

标签: reactjs

我开发自己的反应博客的那天,我遇到了问题,需要你的帮助,而且我的英语很差,请原谅输入错误。

我用React 16.x编写代码,并且反应发出警告:

  

警告:只能更新已安装或安装的组件。这通常意味着您在已卸载的组件上调用了setState,replaceState或forceUpdate。这是一个无操作。   请检查Post组件的代码。

enter image description here

Post Component在ComponentDidMount生命周期方法中使用异步请求调用getCategories()函数,然后在呈现Post Component后单击指向另一个Component的链接,它会发出警告。

我已尝试添加标记:

componentDidMount() {
  this._isMounted = true;

  this.getCategories()
}

componentWillUnmount() {
  this._isMounted = false;
}

然后在我的getCategories中:

fetch({
    ...API.getCategories,
    data: {
      include: post.categories.join(',')
    }
  }).then(res => {
    if (res && res.data && this._isMounted) {
      this.setState(prevState => ({
        meta: Object.assign({}, prevState.meta, {
          categories: res.data
        })
      }));
    }
  });

仍然有警告。

1 个答案:

答案 0 :(得分:2)

在组件装载后更新状态将触发第二次render()调用,并可能导致属性/布局颠簸。您收到此警告是因为您正在componentDidMount()

中设置状态

请阅读this了解详情。

相关问题