我正在尝试更新包含对象的数组。我有条件,如果Select_Item属性不等于Cart_Item中的Item属性,那么将在Cart_Item数组中推送一个新对象。
如果相等,则需要更新Cart_Item对象。代码的更新部分不起作用,也无法读取Cart_Item中的属性。相关代码如下
if (this.state.Item !== this.state.Select_Item) {
let yy = [...(this.state.Cart_Item || [])];
let xx = {
Price: ll,
Item: ll3,
Quantity: this.state.Select_Quantity,
Total_Item_Price: ll6
};
yy.push(xx);
this.setState({ Cart_Item: yy });
} else {
//Cart updata and add objects
// let Cart_Item = this.state.Cart_Item;
let Cart_Item = [...(this.state.Cart_Item || [])];
var index = Cart_Item.findIndex(
obj => obj.Item === this.state.Select_Item
);
Cart_Item[index].Price= ll;
Cart_Item[index].Item = ll3;
Cart_Item[index].Quantity = this.state.Select_Quantity;
Cart_Item[index].Total_Item_Price = ll6;
this.setState({ Cart_Item });
}
console.log(this.state.Cart_Item);
也请参阅沙箱
答案 0 :(得分:0)
有几件事可能对您的代码更好。在“ if语句”的第一部分中,您正在使用spread
运算符,这很好避免了突变。但是然后您在数组中执行了.push
,从而使变量?
展开时,您也不需要“或”(|| []
)即可退回到空数组。
您更新的代码(对于第一部分)可能是这样的:
const updatedCartItem = [
...this.state.Cart_Item,
{
Price: ll,
Item: ll3,
Quantity: this.state.Select_Quantity,
Total_Item_Price: ll6
}
]
this.setState({ Cart_Item: updatedCartItem });
对于“ else语句”,您还将spread
与突变混合在一起。当您需要更改数组中的项目时,一种避免变异的方法是使用.map
函数(more info here)。
简而言之,.map
将迭代您的数组并修改特定项目。您也没有进行检查以确保找到要更新的购物车项目的索引。
有了这些修复,您的“其他声明”可能会像这样:
const updatedCartItem = this.state.Cart_Item.map((item) => {
if (item === this.state.Select_Item) {
// If item found, returns a new object (no mutation) with updated attributes
return {
Price: ll,
Item: ll3,
Quantity: this.state.Select_Quantity,
Total_Item_Price: ll6
}
}
// If item not found, just return the current item as it is.
// This is to make sure you are not removing items from your original array.
return item
})
this.setState({ Cart_Item: updatedCartItem });
一起:
if (this.state.Item !== this.state.Select_Item) {
const updatedCartItem = [
...this.state.Cart_Item,
{
Price: ll,
Item: ll3,
Quantity: this.state.Select_Quantity,
Total_Item_Price: ll6
}
]
this.setState({ Cart_Item: updatedCartItem });
} else {
const updatedCartItem = this.state.Cart_Item.map((item) => {
if (item === this.state.Select_Item) {
// If item found, returns a new object (no mutation) with updated attributes
return {
Price: ll,
Item: ll3,
Quantity: this.state.Select_Quantity,
Total_Item_Price: ll6
}
}
// If item not found, just return the current item as it is.
// This is to make sure you are not removing items from your original array.
return item
})
this.setState({ Cart_Item: updatedCartItem });
}