记React中useState异步更新小坑

问题
在hooks中,修改状态的是通过useState返回的修改函数实现的.它的功能类似于class组件中的this.setState().而且,这两种方式都是异步的.可是this.setState()是有回调函数的,那useState()呢?

问题点:

  1. 它异步且没有回调函数
const [count,setCount] = useState(1)
useEffect(()=> {
    setCount(2,()=>{
      console.log('测试hooks的回调');
    })
    console.log(count);
  },[])

打印信息

可以看到提示 “State updates from the useState() and useReducer() Hooks don’t support the second callback argument. To execute a side effect after rendering, declare it in the component body with useEffect().”是不支持回调函数的形式的。因为setCount是异步的,所以打印count是在改变count之前的。

如果我们想要在打印的时候就拿到最新的值,那么我们可以通过setCount的第二个参数指定依赖项

const [count,setCount] = useState(1)
useEffect(()=> {
    setCount(2)
    console.log(count);
  },[count])

当count发生变化的时候,useEffect就会再次相应,但是这样就会有个问题,当count从1变为2的时候useEffect的回调函数会再次执行,就会分别打印1,2两次。

  useEffect(()=> {
    let currentValue = null
      setCount((preVal)=>{
        currentValue=preVal
        return 2
      })
      if(currentValue!==count){
        console.log(count);
      }
    },[count])

通过添加判断条件,我们可以让想要执行的代码只执行一次

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值