代码之家  ›  专栏  ›  技术社区  ›  Cory Robinson

React组件DidMount()在unMounted组件上激发

  •  3
  • Cory Robinson  · 技术社区  · 10 年前

    一个简单的react组件,从上的数据存储调用一个promise componentDidMount 正在发出警告:

    警告:setState(…):只能更新已安装或正在安装的组件。这通常意味着您在未安装的组件上调用了setState()。这是一个禁止。请检查LocationNameView组件的代码。

    我进行了一些调试 console.log 看看是否 this.isMounted() 是真/假,并且在内部 组件DidMount 此.isMounted() 第一次返回false,然后再次返回true。我不确定文件是否清晰或 组件DidMount 这歪曲了我的推理,但似乎只有在实际安装了组件时才应该调用此方法。

    enter link description here

    componentDidMount: function() {
    
      var self = this;
      // make the request to the backend and replace the loading location text
      Models.Location.find(this.props.location)
        .then(function(location) {
    
            console.log(self.isMounted()); // <--- shows false then true 
    
            self.setState({ location : location });
    
        });
    
    },
    
    1 回复  |  直到 10 年前
        1
  •  5
  •   Community Mohan Dere    8 年前

    componentDidMount 在构建底层DOM表示时调用,但尚未安装到实际DOM。

    显示关于设置未安装组件的状态的警告的原因是,上例中的aSync回调可以在组件实际安装到客户端/浏览器中的DOM树之前返回。

    这里的教训是,如果您使用的是一个aSync回调,它将组件中的状态设置为 componentWillMount 组件DidMount ,首先使用安全锁扣 isMounted() 在进入设置状态之前,即:

    componentDidMount() {
    
      let self = this;
    
      PromiseMethod().then(function aSyncCallback(data) {
    
        if ( self.isMounted() ) {
    
          self.setState({...data});
    
        }
    
      });
    
    }
    

    React Component Lifecycle reference