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

React使用useState存储JSX.Element数组 点击元素后body无更新如何解决

问题原因
  • 第一个useEffect存在语法错误,回调函数闭合后多了多余的)和,,会直接导致逻辑运行异常
  • 把JSX元素存储在state中属于错误实践,增加了多余的渲染依赖链路,容易触发闭包陷阱导致视图不更新
解决方案

直接删除冗余的body状态,不需要通过useEffect监听生成JSX,直接在渲染组件时通过thisState实时计算表格body内容即可,同时修复第一个useEffect的语法错误。

修改后的代码如下:

const reduxSelectorValue = useSelector(state => state.someReducer.value) // [4,5,6,7]
const [thisState, setThisState] = useState<number[]>([1])

// 修复原来的语法错误,删除多余的),
useEffect(()=>{
  setThisState(reduxSelectorValue)
},[reduxSelectorValue])

// 直接在渲染时生成body,不需要额外状态存储
const body = thisState.map((value: number, index: number) => (
  <div
    onClick={() => {
      setThisState((prevState) => {
        const newThisState = prevState.slice()
        // 原逻辑+1-3等价于-2,可直接简化
        newThisState[index] = newThisState[index] - 2
        return newThisState
      })
    }}
  >
    {value}
  </div>
))

render(
  <ATableElement body={body}/>
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 23:45:03