手动移除事件侦听器反应挂钩

Remove event listener manually 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]);

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

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

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