以下是我更新失败的代码

定义的hook状态
const [productList, setProductList] = useState([]);
点击事件,改变数据中enable字段
const onEnable = (row,index) => { const list = productList; list[index].enable
= !list[index].enable; setProductList(list); console.log('onEnable', row); };

其中,productList是上次列表显示的数据,我需要改动productList中enable字段的值,但是我改变数据之后,通过setProductList(list)却不能更新显示,通过查阅资料发现,const list = productList,此时list和productList是同一个对象,因此不能立即更新,我们可以通过解构的形式来更新,以下是正确的代码:
const onEnable = (row,index) => { const list = productList;
list[index].enable = !list[index].enable; setProductList([...list]);
console.log('onEnable', row); };
通过解构为一个新数组之后,就可以更新了。或者也可以通过setProductList(list.slice()),同样能达到更新的效果。

技术
今日推荐
PPT
阅读数 135
下载桌面版
GitHub
百度网盘(提取码:draw)
Gitee
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:ixiaoyang8@qq.com
QQ群:766591547
关注微信