You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native中useState更新后变量仍为null的问题求解

问题原因

React 里的 useState 状态更新是异步的,调用 setIdOld(535) 后,并不会立刻修改当前函数执行上下文里的 idOld 值,此时 idOld 还是初始的 null,所以弹窗会显示 null。

解决方案

有两种实用的处理方式:

方式一:用 useEffect 监听状态变化

当 idOld 完成更新后,在 useEffect 中执行弹窗逻辑:

const [idOld, setIdOld] = useState(null)

useEffect(() => {
  if (idOld !== null) {
    alert(idOld)
  }
}, [idOld]) // 依赖 idOld,状态更新时自动触发

const testing = () => {
  setIdOld(535)
} 

return (
  <View>
    <Text>Home</Text>
    <CustomFloatingLogout bottom={80} onPress={() => testing()} />
    <CustomFloatingLogout onPress={() => logout()} />
  </View>
)

方式二:直接使用要设置的值弹窗

如果只是想确认要设置的数值,没必要依赖状态,直接用变量存值后弹窗:

const testing = () => {
  const newId = 535
  setIdOld(newId)
  alert(newId)
} 

内容的提问来源于stack exchange,提问作者WhoIsDmathz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 19:10:31