reactjs - 如何动态更新数组的一个元素
问题描述
我的组件中有一个状态,例如
const [game,setGame] = useState([0,0,0,0,0,0,0,0,0]);
当我尝试更新它时,我无法做到。我在尝试
setGame([...game,{clickedBox:'red'}])
我在 clickedBox 中获取索引
解决方案
useState 中的设置会替换它保存的全部数据。首先在外部更新您的阵列,然后将其设置回您的状态。
let arr = [...game];
arr[index] = { /* your changes */ };
setGame([...arr)];
推荐阅读
- xaml - 首次绘制控件后,Xamarin.Forms ControlTemplate 绑定失败
- c++ - 为什么 puts() 在仅对某些值使用指针时有一个随机尾随字符
- c++ - C++:推断模板函数的类型时出错
- python - 无效的 Unicode 转义序列 '\u8def6515'; 最多应该是 '\u0010FFFF'
- python - 尝试使用 Scrapy 抓取数据但只得到空白答案
- python - 用于列出正在运行的应用程序/cron 作业的 Unix 脚本,其中包含端口号和主机上的一般信息
- azure - 如何使 azure devops 发布管道单击一次
- python - Opencv(opencv-contrib)在使用对象检测模块(cv2.dnn.readNet)后改变图像的颜色
- ios - 操作无法完成。(OSStatus 错误 561015905。)
- spring-boot - 将 spring-cloud-config 与 spring-cloud-bus 一起使用