我有一个基于类的组件,它使用multitouch向svg添加子节点,效果很好。现在,我正试图更新它,使其使用带有钩子的功能组件,如果没有其他原因,只是为了更好地理解它们。
为了停止浏览器使用触摸事件进行手势,我需要在它们上使用preventDefault
,这要求它们而不是是被动的,并且由于合成反应事件中没有暴露被动配置,我需要使用svgRef.current.addEventListener('touchstart', handler, {passive: false})
。我在componentDidMount()
生命周期挂钩中执行此操作,并在类内的componentWillUnmount()
挂钩中清除它。
当我把它翻译成一个带有钩子的功能组件时,我得到了以下结果:
export default function Board(props) {
const [touchPoints, setTouchPoints] = useState([]);
const svg = useRef();
useEffect(() => {
console.log('add touch start');
svg.current.addEventListener('touchstart', handleTouchStart, { passive: false });
return () => {
console.log('remove touch start');
svg.current.removeEventListener('touchstart', handleTouchStart, { passive: false });
}
});
useEffect(() => {
console.log('add touch move');
svg.current.addEventListener('touchmove', handleTouchMove, { passive: false });
return () => {
console.log('remove touch move');
svg.current.removeEventListener('touchmove', handleTouchMove, { passive: false });
}
});
useEffect(() => {
console.log('add touch end');
svg.current.addEventListener('touchcancel', handleTouchEnd, { passive: false });
svg.current.addEventListener('touchend', handleTouchEnd, { passive: false });
return () => {
console.log('remove touch end');
svg.current.removeEventListener('touchend', handleTouchEnd, { passive: false });
svg.current.removeEventListener('touchcancel', handleTouchEnd, { passive: false });
}
});
const handleTouchStart = useCallback((e) => {
e.preventDefault();
// copy the state, mutate it, re-apply it
const tp = touchPoints.slice();
// note e.changedTouches is a TouchList not an array
// so we can't map over it
for (var i = 0; i < e.changedTouches.length; i++) {
const touch = e.changedTouches[i];
tp.push(touch);
}
setTouchPoints(tp);
}, [touchPoints, setTouchPoints]);
const handleTouchMove = useCallback((e) => {
e.preventDefault();
const tp = touchPoints.slice();
for (var i = 0; i < e.changedTouches.length; i++) {
const touch = e.changedTouches[i];
// call helper function to get the Id of the touch
const index = getTouchIndexById(tp, touch);
if (index < 0) continue;
tp[index] = touch;
}
setTouchPoints(tp);
}, [touchPoints, setTouchPoints]);
const handleTouchEnd = useCallback((e) => {
e.preventDefault();
const tp = touchPoints.slice();
for (var i = 0; i < e.changedTouches.length; i++) {
const touch = e.changedTouches[i];
const index = getTouchIndexById(tp, touch);
tp.splice(index, 1);
}
setTouchPoints(tp);
}, [touchPoints, setTouchPoints]);
return (
<svg
xmlns={ vars.SVG_NS }
width={ window.innerWidth }
height={ window.innerHeight }
>
{
touchPoints.map(touchpoint =>
<TouchCircle
ref={ svg }
key={ touchpoint.identifier }
cx={ touchpoint.pageX }
cy={ touchpoint.pageY }
colour={ generateColour() }
/>
)
}
</svg>
);
}
这引发的问题是,每次进行渲染更新时,事件侦听器都会被删除并重新添加。这导致handleTouchEnd在有机会清除添加的触摸和其他奇怪之处之前被移除。我还发现,除非我用一个手势离开浏览器,触发更新,删除现有的监听器并添加一个新的集合,否则触摸事件就不起作用。
我曾尝试在useEffect中使用依赖项列表,我看到有几个人引用了useCallback和useRef,但我没能让这项工作变得更好(即,删除然后重新添加事件侦听器的日志仍然在每次更新时都会触发)。
有没有办法让useEffect在装载时只激发一次,然后在卸载时清理,或者我应该放弃这个组件的钩子,坚持使用运行良好的基于类的钩子?
编辑
我还尝试将每个事件侦听器移动到它自己的useEffect
中,并获得以下控制台日志:
remove touch start
remove touch move
remove touch end
add touch start
add touch move
add touch end
编辑2
有几个人建议添加一个依赖数组,我试过这样做:
useEffect(() => {
console.log('add touch start');
svg.current.addEventListener('touchstart', handleTouchStart, { passive: false });
return () => {
console.log('remove touch start');
svg.current.removeEventListener('touchstart', handleTouchStart, { passive: false });
}
}, [handleTouchStart]);
useEffect(() => {
console.log('add touch move');
svg.current.addEventListener('touchmove', handleTouchMove, { passive: false });
return () => {
console.log('remove touch move');
svg.current.removeEventListener('touchmove', handleTouchMove, { passive: false });
}
}, [handleTouchMove]);
useEffect(() => {
console.log('add touch end');
svg.current.addEventListener('touchcancel', handleTouchEnd, { passive: false });
svg.current.addEventListener('touchend', handleTouchEnd, { passive: false });
return () => {
console.log('remove touch end');
svg.current.removeEventListener('touchend', handleTouchEnd, { passive: false });
svg.current.removeEventListener('touchcancel', handleTouchEnd, { passive: false });
}
}, [handleTouchEnd]);
但我仍然收到一个日志,说每个useEffect
都被删除了,然后在每次更新时重新添加(所以每个导致油漆的touchstart
、touchmove
或touchend
——这是很多:)
编辑3
我已经用useRef()
替换了window.(add/remove)EventListener
ta
如果只希望在组件安装和卸载时发生这种情况,则需要为useEffect钩子提供一个空数组作为依赖数组。
useEffect(() => {
console.log('adding event listeners');
window.addEventListener('touchstart', handleTouchStart, { passive: false });
window.addEventListener('touchend', handleTouchEnd, { passive: false });
window.addEventListener('touchcancel', handleTouchEnd, { passive: false });
window.addEventListener('touchmove', handleTouchMove, { passive: false });
return () => {
console.log('removing event listeners');
window.removeEventListener('touchstart', handleTouchStart, { passive: false });
window.removeEventListener('touchend', handleTouchEnd, { passive: false });
window.removeEventListener('touchcancel', handleTouchEnd, { passive: false });
window.removeEventListener('touchmove', handleTouchMove, { passive: false });
}
}, []);
非常感谢大家-我们找到了它的底部(w00t)
为了停止组件useEffect
钩子多次触发,需要向钩子提供一个空的依赖数组(如Son Nguyen和wentjun所建议的),但这意味着在处理程序中无法访问当前的touchPoints
状态。
答案(wentjun建议)是在使用useEffect React Hook时如何修复丢失的依赖警告?
其中提到了钩子faq:https://reactjs.org/docs/hooks-faq.html#what-can-i-do-if-my-效果依赖性-更改为经常
这就是我的组件最终的原因
export default function Board(props) {
const [touchPoints, setTouchPoints] = useState([]);
const svg = useRef();
useEffect(() => {
// required for the return value
const svgRef = svg.current;
const handleTouchStart = (e) => {
e.preventDefault();
// use functional version of mutator
setTouchPoints(tp => {
// duplicate array
tp = tp.slice();
// note e.changedTouches is a TouchList not an array
// so we can't map over it
for (var i = 0; i < e.changedTouches.length; i++) {
const touch = e.changedTouches[i];
const angle = getAngleFromCenter(touch.pageX, touch.pageY);
tp.push({ touch, angle });
}
return tp;
});
};
const handleTouchMove = (e) => {
e.preventDefault();
setTouchPoints(tp => {
tp = tp.slice();
// move existing TouchCircle with same key
for (var i = 0; i < e.changedTouches.length; i++) {
const touch = e.changedTouches[i];
const index = getTouchIndexById(tp, touch);
if (index < 0) continue;
tp[index].touch = touch;
tp[index].angle = getAngleFromCenter(touch.pageX, touch.pageY);
}
return tp;
});
};
const handleTouchEnd = (e) => {
e.preventDefault();
setTouchPoints(tp => {
tp = tp.slice();
// delete existing TouchCircle with same key
for (var i = 0; i < e.changedTouches.length; i++) {
const touch = e.changedTouches[i];
const index = getTouchIndexById(tp, touch);
if (index < 0) continue;
tp.splice(index, 1);
}
return tp;
});
};
console.log('add touch listeners'); // only fires once
svgRef.addEventListener('touchstart', handleTouchStart, { passive: false });
svgRef.addEventListener('touchmove', handleTouchMove, { passive: false });
svgRef.addEventListener('touchcancel', handleTouchEnd, { passive: false });
svgRef.addEventListener('touchend', handleTouchEnd, { passive: false });
return () => {
console.log('remove touch listeners');
svgRef.removeEventListener('touchstart', handleTouchStart, { passive: false });
svgRef.removeEventListener('touchmove', handleTouchMove, { passive: false });
svgRef.removeEventListener('touchend', handleTouchEnd, { passive: false });
svgRef.removeEventListener('touchcancel', handleTouchEnd, { passive: false });
}
}, [setTouchPoints]);
return (
<svg
ref={ svg }
xmlns={ vars.SVG_NS }
width={ window.innerWidth }
height={ window.innerHeight }
>
{
touchPoints.map(touchpoint =>
<TouchCircle
key={ touchpoint.touch.identifier }
cx={ touchpoint.touch.pageX }
cy={ touchpoint.touch.pageY }
colour={ generateColour() }
/>
)
}
</svg>
);
}
注意:我将setTouchPoints
添加到依赖项列表中是为了更具声明性的
蒙多尊重
;oB