只能更新一安装或安装组件
问题描述:
我收到以下警告只能更新一安装或安装组件
警告:的setState(...):只能更新一安装或安装 组件。这通常意味着您在未安装的组件上调用了setState()。这是一个没有操作。请检查未定义的 组件的代码。
这是我的代码
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)
}