Had*_*bar 8 reactjs react-router-dom 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]);
Run Code Online (Sandbox Code Playgroud)
我应该在哪里定义 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]);
Run Code Online (Sandbox Code Playgroud)