簡體   English   中英

在 React useEffect hook 中清理 Lodash debounce function

[英]Cleaning up Lodash debounce function in React useEffect hook

我正在嘗試使用 Lodash 的 Debounce function 和自定義掛鈎來防止 window 調整大小事件過於頻繁地觸發。 雖然鈎子按需要工作,但我正在努力正確清理從 React useEffect 鈎子返回的 function。 這會導致瀏覽器控制台中出現以下錯誤,並且單頁應用程序中的所有用戶 session 都存在事件偵聽器。

Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

我知道有一些方法可以滾動自定義 debounce hook,但是為了這個大量使用 Lodash 的項目,如果可能的話,我寧願堅持使用 Debounce function。

function getSize() {
  return {
    width: window.innerWidth,
    height: window.innerHeight,
  };
}

export default function useWindowSize(debounceDelay = 500) {
  const [windowSize, setWindowSize] = useState(getSize);

  useEffect(() => {
    function handleResize() {
      setWindowSize(getSize());
    }

    const debounced = debounce(handleResize, debounceDelay);
    window.addEventListener(`resize`, debounced);

    return () => window.removeEventListener(`resize`, debounced.cancel());
  }, [debounceDelay]);

  return windowSize;
}

不需要通過debounce.cancel() 刪除事件偵聽器時,您需要將相同的引用傳遞給創建偵聽器時使用的 function。 您也可以取消當前的去抖 function。

useEffect(() => {
    function handleResize() {
      setWindowSize(getSize());
    }

    const debounced = debounce(handleResize, debounceDelay);
    window.addEventListener(`resize`, debounced);

    return () => {
         debounce.cancel()
         window.removeEventListener(`resize`, debounced); // use debounced directly
     }
  }, [debounceDelay]);

您是直接調用 cancel function 而不是。 您應該只使用debounced這就是在您的偵聽器中添加的內容:

return () => {
  window.removeEventListener('resize', debounced)
}

在大多數情況下,只需刪除事件就可以了:

return () => {
  window.removeEventListener('resize')
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM