反应事件侦听器,节流阀未被删除

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 returns 每次你 运行 一个新功能;因此,相等性检查将始终失败,并且您将无法删除事件侦听器(不删除 all 事件侦听器)。下面是相等检查中发生的事情的简单演示:

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