首页 > 解决方案 > React-Native Animated 在 setState 附近不起作用

问题描述

let animatedHeight = new Animated.Value(50);

const animate = () => {
    animatedHeight.setValue(50);
    Animated.timing(animatedHeight, {
      toValue: 0,
      duration: 200,
      useNativeDriver: true
    }).start();
  };



  const handleSubmit = async (values:ILoginProps) => {
        setLoading(true);

        axios.post('http://127.0.0.1:3333/api/v1/auth/login', values)
        .then(res => {
            console.log(res);
        })
        .catch(err => {
            console.log(err);
            animate();
            setLoading(false);
        })
    
  }

  <Animated.View style={[style.errorContainer, {transform: [{translateY: animatedHeight}]}]}>
     <Text style={style.errorText}>Credentials not found!</Text>
  </Animated.View>

我有这段代码,首先我设置了一个加载状态,然后执行一个动画函数,该函数运行动画函数来创建动画效果。

当我在 animate() 之前有 setLoading(true) 时,动画不会发生。

我真的不知道为什么会发生这种情况,也不知道如何解决这个问题

标签: react-nativereact-animated

解决方案


使用useRef钩子来包装你的动画值。React 会在重新渲染后继续跟踪它的值,否则你可能会丢失它。

let animatedHeight = React.useRef(new Animated.Value(50)).current;

推荐阅读