首页 > 解决方案 > 使用 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}}}})
        })

图片便于理解

谁能帮忙

标签: javascriptreactjsimmutability-helper

解决方案


使用括号表示法:

setFoodArray((prev) => {
    return update(prev, {[index]: {amount: {$apply: function(x) {return x -1}}}})
})

推荐阅读