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

React.js中无法更新useState:关闭Modal时设所有状态为true

解决方法

方法1:直接生成全true的状态对象

修改hideModal函数,直接创建所有属性为true的对象来更新状态,适合状态属性固定的场景:

const hideModal = (e) => {
  setState({
    one: true,
    two: true,
    three: true
  })
}

方法2:基于初始状态批量生成全true对象

如果后续可能新增状态属性,用遍历的方式批量设置为true,避免重复修改代码:

const hideModal = (e) => {
  const allTrueState = Object.fromEntries(
    Object.keys(initialState).map(key => [key, true])
  )
  setState(allTrueState)
}

方法3:函数式更新(依赖当前状态时使用)

如果需要基于最新的当前状态做修改,使用setState的函数式更新确保拿到最新状态值:

const hideModal = (e) => {
  setState(prevState => {
    return Object.fromEntries(
      Object.keys(prevState).map(key => [key, true])
    )
  })
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 14:18:12