英文:
removeEventListener doesn't work inside useEffect logic
问题
在ReactJS中,如果我有一个类似这样检查observer
的useEffect
:
// ...observer的代码在这里
useEffect(() => {
function handleParallax() {
let items = document.querySelectorAll('.item')
items.forEach(item => {
let distance = (window.scrollY || window.pageYOffset),
distanceFinal = item.parentNode.offsetTop - distance,
multi = 45;
console.log((distanceFinal * multi)/500);
let calc = `translate3d(0, calc(370px + ${((distanceFinal * multi)/500)}px), 0)`;
item.setAttribute('style',
`transform: ${calc};
-ms-transform: ${calc};
-webkit-transform: ${calc};`
);
});
}
if (isIntersecting) {
console.log('enter')
window.addEventListener('scroll', handleParallax, true)
}else{
console.log('exit')
window.removeEventListener('scroll', handleParallax, true);
}
}, [isIntersecting]);
removeEventListener
不起作用,实际上我在浏览器中会收到观察区域进入/退出状态的控制台日志,但在我滚动到观察器范围之外时,handleParallax
函数内部的控制台日志仍然记录,这是为什么?
英文:
In ReactJS, if I have a useEffect
checking for an observer
like this:
// ...observer code here
useEffect(() => {
function handleParallax() {
let items = document.querySelectorAll('.item')
items.forEach(item => {
let distance = (window.scrollY || window.pageYOffset),
distanceFinal = item.parentNode.offsetTop - distance,
multi = 45;
console.log((distanceFinal * multi)/500);
let calc = `translate3d(0, calc(370px + ${((distanceFinal * multi)/500)}px), 0)`;
item.setAttribute('style',
`transform: ${calc};
-ms-transform: ${calc};
-webkit-transform: ${calc};`
);
});
}
if (isIntersecting) {
console.log('enter')
window.addEventListener('scroll', handleParallax, true)
}else{
console.log('exit')
window.removeEventListener('scroll', handleParallax, true);
}
}, [isIntersecting]);
the removeEventListener
doesn't work, in fact I receive a console log in browser of the enter/exit state of the observed area, but the console log inside the handleParallax
function still logs as I scroll outside of the observer bounds, why is that?
答案1
得分: 2
将handleParallax
函数移到组件外部(这是可能的,因为它不使用任何内部组件数据),这样相同的引用将被传递给addEventListener
和removeEventListener
。
英文:
Move the handleParallax
function outside the component (which is possible since it doesn't use any internal component data), so that the same reference will be passed to both addEventListener
and removeEventListener
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论