有没有办法检查反应组件是否被卸载?
答
由于isMounted()
被正式弃用,您可以在您的组件做到这一点:
componentDidMount() {
this._ismounted = true;
}
componentWillUnmount() {
this._ismounted = false;
}
维护自己state
变量的这种模式是ReactJS文档中详细介绍:https://facebook.github.io/react/blog/2015/12/16/ismounted-antipattern.html
答
我发现,组件将被卸载,生成填充此变量
if(!this._calledComponentWillUnmount)this.setState({vars});
答
我到了这里是因为我正在寻找停止polling
API的方法。
react docs确实涵盖了websocket
的情况,但不包括轮询的情况。
我周围
// React component
let allowPolling = true
React.createClass({
poll() {
if (!allowPolling) {
return
}
// otherwise, call the api
}
componentWillMount() {
allowPolling = true
}
componentWillUnmount() {
allowPolling = false
}
})
它的工作的工作方式。希望它可以帮助
请让我知道,如果你们知道任何失败的测试情况下,此=]
答
我认为Shubham答案是对于那些需要转变他们的代码停止使用人们的反应提出了一个解决办法isMounted
反模式。
这不一定是坏事,但它是值得列出真正的解决方案,以解决这个问题。
The article linked by Shubham提供2条建议以避免这种反模式。您需要的一个取决于您在卸载组件时为什么要调用setState。
,如果您使用的是您的组件通量商店,你必须在componentWillUnmount退订
class MyComponent extends React.Component {
componentDidMount() {
mydatastore.subscribe(this);
}
render() {
...
}
componentWillUnmount() {
mydatastore.unsubscribe(this);
}
}
如果使用ES6的承诺,你可能需要包装自己的诺言,以使它可以取消。
const cancelablePromise = makeCancelable(
new Promise(r => component.setState({...}}))
);
cancelablePromise
.promise
.then(() => console.log('resolved'))
.catch((reason) => console.log('isCanceled', reason.isCanceled));
cancelablePromise.cancel(); // Cancel the promise
链接的文章中了解更多关于makeCancelable
。
总之,不要尝试通过设置变量和检查组件是否已装入来修补此问题,请转到问题的根源。如果您能提出任何疑问,请与其他常见情况进行评论。
感谢您对文档的建议...只需在componentDidMount中将_isMounted属性设置为true,并在componentWillUnmount中将其设置为false ...但是,使用此属性。setState({mounted:false});可能会触发太晚,以防止警告,因为状态变化不会立即发生 - 最好只是使用类属性为此... this.mounted = false - 谢谢你,这指出我在正确的方向 – danday74
@ danday74,是啊你是正确的。当我写出答案时,我可能错过了这一点。考虑upvoting如果它的帮助 –
是的我在10天前upvoted :) – danday74