首页 > 解决方案 > 如何动态更新数组的一个元素

问题描述

我的组件中有一个状态,例如

const [game,setGame] = useState([0,0,0,0,0,0,0,0,0]);

当我尝试更新它时,我无法做到。我在尝试

setGame([...game,{clickedBox:'red'}])

我在 clickedBox 中获取索引

标签: reactjs

解决方案


useState 中的设置会替换它保存的全部数据。首先在外部更新您的阵列,然后将其设置回您的状态。

let arr = [...game];
arr[index] = { /* your changes */ };
setGame([...arr)];

推荐阅读