javascript - 使用 Immutability helper js 更新对象数组中对象内的元素
问题描述
我需要使用不变性助手在对象数组中添加或减去元素的值
const selectedFood= [
{id: uuidv4(), name: "pizza", price: 1700, amount: 3},
{id: uuidv4(), name: "cheese", price: 600, amount: 10},
{id: uuidv4(), name: "fried rice", price: 500, amount: 4},
{id: uuidv4(), name: "coke", price: 100, amount: 5}]
const [foodArray, setFoodArray] = useState(selectedFood);
这段代码完美无缺,这就是我想要的,除了索引
setFoodArray((prev) => {
return update(prev, {2: {amount: {$apply: function(x) {return x -1}}}})
})
这里的数字 2 应该是索引
所以我用它来获取索引
const index = foodArray.indexOf(foodArray.find((single) => {
return single.id === id
}));
把这个索引变量放在那里是行不通的
setFoodArray((prev) => {
return update(prev, {index: {amount: {$apply: function(x) {return x -1}}}})
})
谁能帮忙
解决方案
使用括号表示法:
setFoodArray((prev) => {
return update(prev, {[index]: {amount: {$apply: function(x) {return x -1}}}})
})
推荐阅读
- sql - 关于 Tableau Desktop 如何与超大型数据库对话的简单问题
- spring - 在不配置 CORS 的情况下将文件从 Angular 上传到 Spring
- reactjs - 创建客户端时无法连接到 twilsock
- android - 结合 Android 附近连接和视频
- .htaccess - .htaccess 代码使 url 小写并在需要时添加斜杠,有时会添加额外的斜杠。任何想法如何解决它?
- android - 如何通过在 Kotlin 中提供大小来创建数组
- android - 如何从图标中删除白色背景?
- css - 我可以使用 css 更改内联数据属性(数据视差)的值吗?
- google-chrome - 如何在观看视频时下载 Google Chrome 浏览器存储的 blob 数据?
- android - Android中的空对象引用