我正在尝试使用useState和useEffect实现包装组件的动画效果。如果props上的某个值发生改变,我希望它能触发动画的开始:
const propVal = getter(props);
const mounted = useRef(true);
useEffect(() => {
//code to initialize and start animation removed
//because a started animation uses requestAnimationFrame
//a component may want to set state for animation while not
//mounted anymore, prevent the error by setting mounted to false
return () => (mounted.current = false);
}, [propVal]);//<--if propVal changes the animation starts
完整代码在这里
propVal
可以是一个项目的ID(新项目将带有动画效果),也可以是名为deleted
的属性,表示已删除项目(应该带有动画效果)。
我正在尝试创建一个更小的代码示例来重现我所面临的问题,但尚未能够做到。
问题是,如果我删除一个项目,那么即使组件没有卸载,mounted.current = false
(从useEffect
返回的回调)部分也会被调用。
当我将代码更改为return () => false && (mounted.current = false);
,基本上是删除了防护措施以防止未安装的组件进行动画处理,然后删除项目将会出现动画而不会出错。这告诉我组件没有被卸载,但是某种方式触发了返回的onUnmount的回调函数。
很抱歉目前还无法提供更简单的问题复现,也许有人知道当组件显然没有卸载时为什么会调用回调函数。