reactjs - React componentDidMount() 在未安装的组件上被触发

标签 reactjs setstate

componentDidMount 上的数据存储调用 promise 的简单 react 组件抛出警告:

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 LocationNameView component.

我调试了一些 console.log 来查看 this.isMounted() 是否为真/假,以及 componentDidMount >this.isMounted() 第一次会返回 false,然后再次返回 true。我不确定文档是否清楚,或者 componentDidMount 的名称是否歪曲了我在这里的推理,但似乎只有在实际安装组件时才应调用此方法。

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

    });

},

最佳答案

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

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

这里的教训是,如果您使用的是在 componentWillMountcomponentDidMount 上设置组件状态的同步回调,请首先使用安全捕获器 isMounted( ) 在继续设置状态之前,即:

componentDidMount() {

  let self = this;

  PromiseMethod().then(function aSyncCallback(data) {

    if ( self.isMounted() ) {

      self.setState({...data});

    }

  });

}

React Component Lifecycle reference

关于reactjs - React componentDidMount() 在未安装的组件上被触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34539884/

相关文章:

javascript - 使用 React js 调用两个以上的 Web 服务并将它们填充到 Material ui 下拉列表中

reactjs - 如何使用 jest 和 RTL 模拟来自 react 组件的异步操作调用

javascript - React 中的 setState : How to create a variable the value for which is dependent on another variable's value

javascript - React 方法中多次调用 setState() : How to make it work "synchronously"

flutter - 如何从另一个小部件状态处理一个小部件状态?

javascript - 如何添加第二个按钮而不导致堆栈崩溃?

javascript - 仅对一个变量设置状态

javascript - 如何等到所有图片上传到firebase才调用函数

reactjs - 如何验证传递给 Formik 中匿名组件的 props?

css - 根据字符数更改行高