React-Native State状态 易混淆点

  前言     

        今天,我写了一个评论区展开动画,利用state控制是否展开评论区,然后犯了一个低级错误,就是state更改后不会立即更新,从而导致动画未能达到理想状态。

错误示范

1. 分别声明一个控制评论区显示的state控制评论区高度的state(因为后面要用到Animated动画,所以要使用Animated的写法,并分别给一个默认值false和默认值0,也就是默认情况下不展开评论区。

const [showComment, setShowComment] = useState(false);

const [commentHeight] = useState(new Animated.Value(0));

2. 创建一个按钮和评论区盒子

// 按钮
<Pressable style={{position:'absolute',width:50,height:50,right:10,top:10}} onPress={toggleComment}>
    <Text>点击打开评论区</Text>
</Pressable>

// 评论区盒子

<Animated.View style={{height:commentHeight,width:'100%',backgroundColor:'white'}}>
    {<View>主要内容</View>}
</Animated.View>

3. 创建动画,这里我将评论区高度设置为hp(60),这里的hp(60)就是高度的60%,我是使用了这个库react-native-responsive-screen - npm,因为这样可以提高写代码效率。

        然后我的错误就是从此刻开始的,我预想的情况是:点击按钮后调用toggleComment函数,然后利用setShowComment(!showComment); 将showComment变为true,这样下面的Animated的toValue: showComment ? hp(60) : 0 就会使用hp(60)。

        但是,state在值更改后并不会立即更新,所以其实在点击按钮后,执行Animated还是false,得需要点击两次按钮才会打开评论区。这样的效果并不理想。

// 先导入动画库
import { Animated } from 'react-native'

// 写切换评论区的函数和动画参数

const toggleComment = () => {
    setShowComment(!showComment);

    Animated.timing(commentHeight, {
      toValue: showComment ? hp(60) : 0, // 控制评论区的高度,如果showComment值为true就高度展开为hp(60),否则就变为0
      duration: 500, // 动画持续时间
      useNativeDriver: false, // 在 Android 设备上使用 native driver 时可能会出现问题
    }).start();
  };

解决方案

        在声明的时候直接把值设置为true,其他代码依旧

const [showComment, setShowComment] = useState(true);

const [commentHeight] = useState(new Animated.Value(0));

  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值