手动移除事件监听器反应钩子

Had*_*bar 8 reactjs react-router-dom react-hooks

我有一个滚动事件侦听器,我想根据页面 URL 删除它,如何在钩子组件中使用它来处理它?

 useEffect(() => {
    function handleScrollEvent() {
      if (window.scrollY > 100) {
        setHeaderIsVisible(true);
      } else {
        setHeaderIsVisible(false);
      }
    }
    if (props.location.pathname === "/") {

      window.addEventListener("scroll", handleScrollEvent, true);
    } else {
      window.removeEventListener("scroll", handleScrollEvent, true);
    }
  }, [props.location.pathname]);
Run Code Online (Sandbox Code Playgroud)

我应该在哪里定义 handleScrollEvent 以将其从侦听器中删除?

Ven*_*sky 7

您需要做的是每次添加它时,您也将其删除。

props.location.pathname更改时,它将删除事件侦听器。

useEffect(() => {
    if (props.location.pathname === "/") {  
      function handleScrollEvent() {
        if (window.scrollY > 100) {
          setHeaderIsVisible(true);
        } else {
          setHeaderIsVisible(false);
        }
      }

      window.addEventListener("scroll", handleScrollEvent, true);  
      // every time you add it, you also remove it when props.location.pathname changes
      return () => {
           window.removeEventListener("scroll", handleScrollEvent, true);
      }
    }
  }, [props.location.pathname]);
Run Code Online (Sandbox Code Playgroud)

  • @HadiRanjbar:如果组件已卸载,为什么要保留此事件侦听器?这似乎会导致内存泄漏。 (2认同)
  • 那么你的第一条评论就更令人困惑了。当“props.location.pathname”更改时,useEffect将在每次更新之前执行清理。并且也在卸载时。文档中有详细解释:https://reactjs.org/docs/hooks-effect.html#effects-with-cleanup (2认同)