[英]React Native animation useEffect hook with dependencies array creates infinite loop
I am trying to figure out how to make eslint with the rule react-hooks/exhaustive-deps
happy and also use the build in Animated
library in react native to make animations with useEffect.我试图弄清楚如何使用规则
react-hooks/exhaustive-deps
使 eslint 满意,并在 react native 中使用Animated
库中的构建来制作带有 useEffect 的动画。
The following code should highlight the button when clicked, by overlaying it with a colored view.以下代码应在单击时突出显示该按钮,并用彩色视图覆盖它。
const Component = props => {
const [active, setActive] = useState(false);
const [opacity, setOpacity] = useState(new Animated.Value(0));
useEffect(() => {
if (active) {
Animated.timing(opacity, {
toValue: 1,
duration: 200,
useNativeDriver: true
}).start();
} else {
setOpacity(new Animated.Value(0))
}
}, [active, opacity]); // <- Works fine without `opacity`, but eslint wants this
return (
<View>
<Animated.View style={{backgroundColor: "blue", opacity}} />
<TouchableOpacity onPress={()=> setActive(!active)} />
</View>
)
};
Is there any way of doing this (with useCallback, useMemo, etc.) without disabling the rule?有没有办法在不禁用规则的情况下执行此操作(使用 useCallback、useMemo 等)?
You don't need to call setOpacity
, instead you can use setValue
:您不需要调用
setOpacity
,而是可以使用setValue
:
opacity.setValue(0)
There is also no need to add opacity
to dependencies, because it never changes.也不需要为依赖项添加
opacity
,因为它永远不会改变。 ESLint doesn't always get it right. ESLint 并不总是正确的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.