【发布时间】:2018-02-16 13:39:32
【问题描述】:
我的代码如下所示:
componentDidMount() {
window.addEventListener('resize', this.resize);
}
componentWillUnmount() {
window.removeEventListener('resize', this.resize);
}
resize = () => this.forceUpdate();
这很好用。但后来我尝试添加一个油门以获得更好的性能
componentDidMount() {
window.addEventListener('resize', _.throttle(this.resize, 200));
}
componentWillUnmount() {
window.removeEventListener('resize', this.resize);
}
resize = () => this.forceUpdate();
但是当我在不同的视图中调整屏幕大小时,我收到了这个错误警告:
Warning: forceUpdate(...): Can only update a mounted or mounting component. This usually means you called forceUpdate() on an unmounted component. This is a no-op. Please check the code for the component.
这意味着我没有正确删除监听器。如何删除带有节流阀的侦听器?还是应该把油门放在别的地方?
我尝试更新componentWillUnmount 喜欢这个:
componentWillUnmount() {
window.removeEventListener('resize', _.throttle(this.resize, 200));
}
但这也不起作用。
任何想法
【问题讨论】:
标签: javascript reactjs addeventlistener throttling