我正在 reactjs-flux 上编写一个简单的应用程序,一切正常,除了我收到来自 reactjs 的警告,告诉我我正在对未安装的组件调用 setState。
我发现这是因为没有从componentWillUnmount
. 我知道这是因为当我打印监听器列表时,Eventemitter
我看到应该被销毁的监听器仍然在那里,并且随着我多次安装/卸载相同的组件,列表变得更大。
我从 BaseStore 粘贴代码:
import Constants from '../core/Constants';
import {EventEmitter} from 'events';
class BaseStore extends EventEmitter {
// Allow Controller-View to register itself with store
addChangeListener(callback) {
this.on(Constants.CHANGE_EVENT, callback);
}
removeChangeListener(callback) {
this.removeListener(Constants.CHANGE_EVENT, callback);
}
// triggers change listener above, firing controller-view callback
emitChange() {
this.emit(Constants.CHANGE_EVENT);
}
}
export default BaseStore;
我粘贴了遇到此错误的组件中的相关代码(尽管所有组件都会发生这种情况):
@AuthenticatedComponent
class ProductsPage extends React.Component {
static propTypes = {
accessToken: PropTypes.string
};
constructor() {
super();
this._productBatch;
this._productBatchesNum;
this._activeProductBatch;
this._productBlacklist;
this._searchById;
this._searchingById;
this.state = this._getStateFromStore();
}
componentDidMount() {
ProductsStore.addChangeListener(this._onChange.bind(this));
}
componentWillUnmount() {
ProductsStore.removeChangeListener(this._onChange.bind(this));
}
_onChange() {
this.setState(this._getStateFromStore());
}
}
这让我在这一点上非常疯狂。有任何想法吗?
谢谢!