[英]Cannot remove an event listener outside useEffect
I add an event listener inside useEffect
. 我在
useEffect
添加了一个事件监听useEffect
。 It runs once after first rerender due to the useEffect second argument( []
) . 由于useEffect第二个参数(
[]
),它在第一次重新渲染后运行一次。 Then I try to remove it outside useEffect
(in handleSearch function) but it doesn't work. 然后我尝试在
useEffect
(在handleSearch函数)之外删除它,但它不起作用。 I suspect it has something to do with function scopes but don't understand it fully. 我怀疑它与功能范围有关,但不完全理解。 Maybe there is a workaround?
也许有一个解决方法?
const handleSearch = () => {
window.removeEventListener('resize', setPageHeightWrapper);
};
const [pageHeight, setPageHeight] = useState(0);
function setPageHeightWrapper() { setPageHeight(window.innerHeight); };
useEffect(() =>{
window.addEventListener('resize', setPageHeightWrapper);
return () => {
window.removeEventListener('resize', setPageHeightWrapper);
};
}, []);
The reason it doesn't work is because setPageHeightWrapper
is defined an inline function and when the component re-renders a new instance of it is created and while clearing an event listener you need to pass the same method which was passed while setting the listener. 它不起作用的原因是因为
setPageHeightWrapper
被定义为内联函数,并且当组件重新呈现它的新实例时,并且在清除事件侦听器时,您需要传递在设置侦听器时传递的相同方法。
On the other hand, when a useEffect hook is called it, gets the function reference from its closure and it uses the same reference to clear the listener. 另一方面,当调用useEffect钩子时,从其闭包中获取函数引用,并使用相同的引用来清除侦听器。
A way to make the removeListener work outside of useEffect is to use useCallback
hook 使removeListener在useEffect之外工作的一种方法是使用
useCallback
钩子
const handleSearch = () => {
window.removeEventListener('resize', memoHeightWrapper);
};
const [pageHeight, setPageHeight] = useState(0);
const memoHeightWrapper = useCallback(() => {
setPageHeight(window.innerHeight);
})
useEffect(() =>{
window.addEventListener('resize', memoHeightWrapper);
return () => {
window.removeEventListener('resize', memoHeightWrapper);
};
}, []);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.