我收到以下警告
“警告:setState(…):只能更新已安装或正在安装的组件。这通常意味着您在未安装的组件上调用了 setState()。这是一个空操作。请检查 ContactPage 组件的代码。”
当我第一次访问联系页面时,一切正常。然后,如果我离开页面并返回,则会引发警告。
联系页面组件:
import React, { Component, PropTypes } from 'react';
import AppStore from '../../stores/AppStore';
import AppActions from '../../actions/AppActions';
import DataContent from './DataContent';
const title = 'Contact Us';
class ContactPage extends Component {
constructor(props) {
super(props);
this.state = AppStore.getState();
AppActions.getData();
}
static contextTypes = {
onSetTitle: PropTypes.func.isRequired,
};
componentWillMount() {
this.context.onSetTitle(title);
AppStore.listen(this.onChange.bind(this));
}
componentWillUnmount() {
AppStore.unlisten(this.onChange.bind(this));
}
onChange(state) {
this.setState(state);
}
renderData() {
return this.state.data.map((data) => {
return (
<DataContent key={data.id} data={data} />
)
})
}
render() {
return (
<div className={s.root}>
<div className={s.container}>
<h1>{title}</h1>
<div>
{ this.renderData() }
</div>
</div>
</div>
);
}
}
export default ContactPage;
当我放入调试器时,在加载联系页面时它会触发 componentWillMount()。当我离开联系页面时,它会触发 componentWillUnmount()。当我导航回页面时,它再次点击 componentWillMount() ,然后在点击 onChange(state) 函数时抛出错误。
原文由 erichardson30 发布,翻译遵循 CC BY-SA 4.0 许可协议
问题是前一个组件实例的侦听器仍然被注册。并且由于不再安装先前的实例,您会收到该错误。
.bind
总是返回一个 新 函数。所以如果你这样做那么您正在尝试删除一个不存在的侦听器(当然会失败)。它 不会 删除您注册的侦听器
AppStore.listen(this.onChange.bind(this))
要解决这个问题,您应该在构造函数中绑定 一次 处理程序:
然后使用
AppStore.listen(this.onChange)
和AppStore.unlisten(this.onChange)
。