我收到以下警告
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 undefined component.
这是我的代码
var React = require('react');
import DetectUtil from 'pofod/detectUtil';
function withSubscription(WrappedComponent,MobileComponent) {
class Subscription extends React.Component{
constructor(props){
super(props);
this.state={
ExternalComponent:innerWidth>1023?WrappedComponent:MobileComponent
}
this.getPageLangParams=this.getPageLangParams.bind(this);
this.MonitorSize = this.MonitorSize.bind(this);
}
getPageLangParams () {
var query=this.props.location?(this.props.location.query?this.props.location.query:{}):{};
var lang=this.props.lang||query.lang||DetectUtil.languageFamily()||'zh';
return lang;
}
MonitorSize(){
this.setState({
ExternalComponent:innerWidth>1023?WrappedComponent:MobileComponent
})
}
componentDidMount(){
window.addEventListener('resize',this.MonitorSize)
}
componentWillMount(){
window.removeEventListener('resize',this.MonitorSize)
}
render(){
let lang = this.getPageLangParams();
let ExternalComponent = this.state.ExternalComponent;
return (
<ExternalComponent lang={lang}/>
)
}
}
return Subscription;
}
module.exports = withSubscription;
最佳答案
您混淆了 componentWillMount 和 componentWillUnmount。
EventListener 正在 componentWillMount 上移除,但您应该在卸载之前移除它,例如componentWillUnmount.
因此,当卸载组件时,MonitorSize 停止触发。 它应该是这样的:
componentWillUnmount(){
window.removeEventListener('resize',this.MonitorSize)
}
关于javascript - 只能更新已安装或正在安装的组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43651364/