Reactjs,删除 componentWillUnmount 上的事件侦听器,

Reactjs, removing event listener on componentWillUnmount,

我有一个小型 React 应用程序。在我的一个主要组件中,我在 componentDidMount 上添加了一个事件侦听器,但是当我尝试在 componentWillUnmount 上删除它时,它似乎并没有这样做。我什至试过把它们一个接一个地放,但似乎还是没有被删除。

这里是我的情况的示例代码(从真实的情况下减少)

listenerF(e){
  console.log('im scrolling!'
  //..actually does other stuff
}

componentDidMount(){
    window.addEventListener('scroll', e => this.listenerF(e))
}

componentWillUnmount(){
    window.removeEventListener('scroll',e=>this.listenerF(e))
    console.log('unmounted')
}

我怀疑它可能是充当匿名函数的箭头函数,因此 removeEventListener 没有正确匹配这些函数。

我尝试了一些替代方法来添加事件侦听器,仅使用函数调用或不使用箭头函数,但它似乎没有那样工作,所以我不确定事件的语法或设置可能有什么问题正在正确添加,但无法删除它

这里的问题是您使用了两个不同的函数:一个是在您添加事件侦听器(箭头函数)时创建的。当您尝试删除侦听器(箭头功能)时使用的另一种方法。

如文档所述:

The event listener to be removed is identified using a combination of the event type, the event listener function itself, and various optional options that may affect the matching process.

https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener

React 自动将事件注入您的处理程序,无需将其包装在箭头函数中只是为了传递事件,问题是 React 没有引用您传递给处理程序的函数。

listenerF(e) { // dont forget to add the event as a parameter here
  console.log(e);
  console.log("im scrolling!");
}

componentDidMount() {
  window.addEventListener("scroll", this.listenerF);
}

componentWillUnmount() {
  window.removeEventListener("scroll", this.listenerF);
  console.log("unmounted");
}