无法删除滚动侦听器

时间:2020-10-15 18:43:26

标签: reactjs

LandingPage.js

我在安装时添加了滚动事件监听器

componentDidMount() {
    window.addEventListener('scroll', this.scrollNavigation, true);
}

我在卸载之前将其删除

componentWillUnmount() {
    window.removeEventListener('scroll', this.scrollNavigation);
    console.log("unmountedLandingPage")
  }

功能

scrollNavigation = () => {
        console.log("called")
        const doc = document.documentElement;
        const top = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0);
        if (top > 80) {
          document.getElementById('topnav').classList.add('nav-sticky');
        } else {
          document.getElementById('topnav').classList.remove('nav-sticky');
        }
      }

问题

当我转到另一页时,看到打印了“ unmontedLandingPage”。但是,当我滚动到那里时,我仍然看到“被叫”被打印出来。为什么我的removeEventListener不起作用?

2 个答案:

答案 0 :(得分:2)

您必须将true传递到removeEventListener调用:

componentWillUnmount() {
    window.removeEventListener('scroll', this.scrollNavigation, true);
    console.log("unmountedLandingPage")
  }

来自docs

尽管addEventListener()可以让您添加相同的侦听器多于 如果选项不同,则一次用于同一类型,唯一的选项 removeEventListener()检查是capture / useCapture标志。它的价值 必须匹配removeEventListener()才能匹配,但是其他值必须匹配 不要。

答案 1 :(得分:1)

如果一个监听程序注册了两次,一个注册了捕获,另一个没有注册,则分别删除每个。删除捕获的侦听器不会影响同一侦听器的非捕获版本,反之亦然。

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

因此,在您的情况下,您正在注册一个捕获的侦听器,但试图删除一个非捕获的侦听器。这行不通。