gpt4 book ai didi

javascript - 当其中一个字段是数组时如何更改状态对象?

转载 作者:行者123 更新时间:2023-11-30 07:12:21 24 4
gpt4 key购买 nike

我有一个这种形式的状态树:

    const initialState = {
total: 0,
discount: 0,
typeDiscount: 0,
products: data
};

其中products字段是一个数组,数组是这样的:

[{
"id":9090,
"name":"Item1",
"price":200,
"discount":10,
"type":"fiction",
"quantity": 1,
"img_url":"https://store.lexisnexis.com.au/__data/media/catalog/thumb//placeholder.jpg"
},
{
"id":9091,
"name":"Item2",
"price":250,
"discount":15,
"type":"literature",
"quantity": 1,
"img_url":"https://store.lexisnexis.com.au/__data/media/catalog/thumb//placeholder.jpg"
}]

现在我正在尝试更改该数组中的数量,我是 Redux 的新手,请指导我如何操作?

这是我的 reducer :

case types.ADD_ITEM_CART:
let product_add = state.products
for (let i = 0; i < product_add.length; i++) {
if (product_add[i].id === action.id) {
product_add[i].quantity = product_add[i].quantity + 1
break
}
}
return dotProp.set(state, `products`, product_add);

最佳答案

您可以使用 Array.prototype.map并迭代项目并更新与负载中的 id 匹配的项目。

类似的东西:

const state = [{
"id": 9090,
"name": "Item1",
"price": 200,
"discount": 10,
"type": "fiction",
"quantity": 1,
"img_url": "https://store.lexisnexis.com.au/__data/media/catalog/thumb//placeholder.jpg"
},
{
"id": 9091,
"name": "Item2",
"price": 250,
"discount": 15,
"type": "literature",
"quantity": 1,
"img_url": "https://store.lexisnexis.com.au/__data/media/catalog/thumb//placeholder.jpg"
}
];

const payload = {
id: 9091
};

const nextState = state.map(product => {
if (product.id !== payload.id) {
// not our product, return as is
return product;
}
return {
...product,
quantity: product.quantity + 1
}
});

console.log(nextState);
.as-console-wrapper {
max-height: 100% !important;
}

要删除项目,您可以使用 Array.prototype.filter :

const state = [{
"id": 9090,
"name": "Item1",
"price": 200,
"discount": 10,
"type": "fiction",
"quantity": 1,
"img_url": "https://store.lexisnexis.com.au/__data/media/catalog/thumb//placeholder.jpg"
},
{
"id": 9091,
"name": "Item2",
"price": 250,
"discount": 15,
"type": "literature",
"quantity": 1,
"img_url": "https://store.lexisnexis.com.au/__data/media/catalog/thumb//placeholder.jpg"
}
];

const payload = {
id: 9091
};

const nextState = state.filter(product => product.id !== payload.id);

console.log(nextState);

关于javascript - 当其中一个字段是数组时如何更改状态对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52573076/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com