【发布时间】:2020-05-13 16:08:18
【问题描述】:
我正在尝试将 Lodash 的 Debounce 函数与自定义挂钩一起使用,以防止窗口调整大小事件过于频繁地触发。虽然钩子按需要工作,但我正在努力正确清理从 React useEffect 钩子返回的函数。这会导致浏览器控制台中出现以下错误,并且单页应用程序中的整个用户会话都存在事件侦听器。
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 挂钩,但是为了这个大量使用 Lodash 的项目,如果可能的话,我更愿意坚持使用 Debounce 功能。
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;
}
【问题讨论】:
标签: javascript reactjs lodash