繁体   English   中英

没有删除节流的React事件侦听器

[英]React event listener with throttle not being removed

我的代码看起来像这样:

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));
}

但这也行不通。

有任何想法吗

也许您可以在构造函数中设置限制:

constructor(props) {
   ...
   this.throttledResize = _.throttle(this.resize, 200)
}

componentDidMount() {
    window.addEventListener('resize', this.throttledResize);
}

componentWillUnmount() {
    window.removeEventListener('resize', this.throttledResize);
}

为了详细阐述其工作原理, window.removeEventListener必须查看目标和事件的所有已注册事件侦听器,并对传递给它的事件处理程序执行相等性检查 - 如果找到匹配项,则将其删除。 这是一个天真的实现:

window.removeEventListener = function(event, handler) {
   // remove the supplied handler from the registered event handlers
   this.eventHandlers[event] = this.eventHandlers[event].filter((evtHandler) => {
       return evtHandler !== handler;
   })
}

_.throttle每次运行时_.throttle返回一个新函数; 因此,相等检查将始终失败,您将无法删除事件侦听器(不删除所有事件侦听器)。 以下是对等式检查发生的事情的简单演示:

 function foo() {} function generateFunction() { // just like throttle, this creates a new function each time it is called return function() {} } console.log(foo === foo) // true console.log(generateFunction() === generateFunction()) // false 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM