从 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
的名称是否歪曲了我在这里的推理,但似乎只有在实际安装组件时才应调用此方法。
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 树之前返回。
这里的教训是,如果您使用的是在 componentWillMount
或 componentDidMount
上设置组件状态的同步回调,请首先使用安全捕获器 isMounted( )
在继续设置状态之前,即:
componentDidMount() {
let self = this;
PromiseMethod().then(function aSyncCallback(data) {
if ( self.isMounted() ) {
self.setState({...data});
}
});
}
关于reactjs - React componentDidMount() 在未安装的组件上被触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34539884/