React里的setState和useState的set函数是异步的

本文探讨了React中useState钩子的异步性质,导致状态更新不立即反映的问题。当age达到18时,<p>Adult</p>不会立即显示。使用async和await无法解决这个问题,因为useState的更新是异步的,并且在同一个渲染周期内state被视为不变。为了解决这个问题,文章介绍了如何利用useEffect来监听age变化,从而正确地更新isAdult状态。
摘要由CSDN通过智能技术生成
import { useState } from 'react'

function App() {
  const [age, setAge] = useState(16)
  const [isAdult, setIsAdult] = useState(false)
  function growUp() {
    setAge(prev => prev + 1)
    if (age === 18) setIsAdult(true)
  }
  return (
    <div>
      {isAdult && <p>Adult</p>}
      <button onClick={growUp}>grow up</button>
      <p>{age}</p>
    </div>
  )
}

export default App

上面一段代码中的<p>Adult</p>不会在age达到18立即显示,而是在19的时候显示

在growUp函数前面加个async,setAge前面加个await也没有用

如果不用函数组件和useState,用class组件和setState结果也一样

要用useEffect才行:

import { useEffect, useState } from 'react'

function App() {
  const [age, setAge] = useState(16)
  const [isAdult, setIsAdult] = useState(false)
  function growUp() {
    setAge(prev => prev + 1)
  }
  useEffect(() => {
    if (age === 18) setIsAdult(true)
  }, [age])
  return (
    <div>
      {isAdult && <p>Adult</p>}
      <button onClick={growUp}>grow up</button>
      <p>{age}</p>
    </div>
  )
}

export default App

stack overflow 上面一篇是这样解释的:

Much like setState in Class components created by extending React.Component or React.PureComponent, the state update using the updater provided by useState hook is also asynchronous, and will not be reflected immediately.

Also, the main issue here is not just the asynchronous nature but the fact that state values are used by functions based on their current closures, and state updates will reflect in the next re-render by which the existing closures are not affected, but new ones are created. Now in the current state, the values within hooks are obtained by existing closures, and when a re-render happens, the closures are updated based on whether the function is recreated again or not.

If async was the only reason, it would be possible to await setState().

However, both props and state are assumed to be unchanging during 1 render.

Treat this.state as if it were immutable.

With hooks, this assumption is enhanced by using constant values with the const keyword:

也就是说state在每一次渲染中是不变的,要等到下次渲染才改变

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值