React:只能更新已安装或正在安装的组件

React: Can only update a mounted or mounting component

本文关键字:安装 组件 更新 React      更新时间:2024-01-07

这是我的组件:

var booksRef = new Firebase("https://bookshelf.firebaseio.com/books");
class BookShelf extends React.Component {
    constructor(props){
      super(props);
      this.state = {books: [] };
      var self = this;
      booksRef.on("value", function(snapshot){
        const newbooks = [];
        var firebaseBooks = snapshot.val();
        for(var bookId in firebaseBooks){
            newbooks.push({key: bookId, book: firebaseBooks[bookId]});
        }
        var newState = self.state;
        newState.books = newbooks;
        self.setState(newState);
      });
    }
   ...

当我第一次导航到此组件时,没有问题。但是,当我导航到另一个组件,然后再次返回到此组件时,我在控制台中收到以下警告:

Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the  component.

我想在处理组件之前我需要做点什么,但我不知道为什么。

对于您的问题,上面类构造函数中的所有代码都是在安装其本质:componentWillMount之前完成的,因此逻辑只在此时运行。

现在一切都很好,但问题很复杂——购买firebase的异步请求。过去有一个名为isMounted的方法,您只需对其进行检查,但现在该方法已被弃用,您的场景的最佳实践概述如下:https://facebook.github.io/react/blog/2015/12/16/ismounted-antipattern.html

查看此博客文章,了解解决此问题的其他(但很技巧)方法:http://jaketrent.com/post/set-state-in-callbacks-in-react/

滚动到es6部分,第一个部分并不直接相关。

附加

看看这篇babel博客文章:特别是关于课程的部分:不确定你是否需要它,但它的很好

https://babeljs.io/blog/2015/06/07/react-on-es6-plus