1 回答
TA贡献1851条经验 获得超3个赞
根据 Carlene 在评论中推荐的问题,我会说没有必要删除事件侦听器,因为它将由垃圾收集器处理,尽管在这种情况下某些较旧的浏览器可能会泄漏内存。
而且,我找到了一种在卸载之前删除侦听器的方法Backdrop_DIV
,它可以工作:
我添加了
lastOpenState_ref
useRef()
对先前渲染open
状态的跟踪,以便我可以检测将卸载Backdrop_DIV
(open === false
)的渲染,并在该渲染期间移除侦听器。
import React, {useState, useEffect, useRef, useCallback} from 'react';
function MyComponent() {
const [open,setOpen] = useState(false);
const backdrop_ref = useRef(null);
const lastOpenState_ref = useRef(false);
const handleBackdropTouchMove = useCallback(() => {
setOpen(false);
},[]);
// BLOCK TO REMOVE EVENT LISTENER FROM backdrop_ref
// SINCE IT'S IMPOSSIBLE TO REMOVE FROM THE useEffect RETURN
// BECAUSE THE backdrop_ref IS NULL WHEN IT RUNS
if (lastOpenState_ref.current === true && open === false) {
backdrop_ref.current.removeEventListener('touchmove', handleBackdropTouchMove);
}
lastOpenState_ref.current = open;
// EFFECT TO ATTACH 'touchmove' EVENT LISTENER ON 'backdrop_ref.current'
useEffect(() => {
if (open) {
backdrop_ref.current.addEventListener('touchmove', handleBackdropTouchMove);
}
},[open,handleBackdropTouchMove]);
// RETURN STATEMENT
return(
<LS.Container_DIV>
{open &&
<LS.Backdrop_DIV
onClick={handleBackdropClick}
ref={backdrop_ref}
>
</LS.Backdrop_DIV>
}
<SomeOtherStuff/>
</LS.Container_DIV>
);
}
添加回答
举报