我是编程新手。我正在尝试更新购物车项目。在模式中单击“确定”的实例时,将更新One_item对象。然后,该对象将传递到Cart_Item数组,该数组包含项目总数。
我试图在Menu组件的Listval()函数中编写逻辑。 One_Item已正确更新。 但是Listval()底部的if条件正在添加,但没有更新。第一次单击也会给出一个空对象。
请查看沙箱: https://codesandbox.io/s/hardcore-stallman-98o58
要研究的相关功能:
Listval() {
let ll = "$" + this.state.listvalue.replace(/[^0-9]/g, "");
let ll2 = this.state.listvalue.replace(/\d+/g, "");
let ll3 = ll2.replace(/\$/g, "");
let ll4 = ll.replace(/\$/g, "");
let ll5 = this.state.Select_Quantity;
let ll6 = parseFloat(ll4) * ll5;
let ll7 = this.state.Total_Item || [];
ll7.push(ll3);
ll7 = [...new Set(ll7)];
this.setState(
{
Select_Price: ll,
Select_Item: ll3,
Select_Item_TotalPrice: ll6,
Total_Item: ll7
},
() => {
// CHANGE: Use callback function to send data to the parent component
this.props.updateTotalItems(this.state.Total_Item.length);
}
);
// append new object This is where problem starts, the new object pushes at second click
if (this.state.Item !== this.state.Select_Item) {
let xx = {
Price: ll,
Item: ll3,
Quantity: this.state.Select_Quantity,
Total_Item_Price: ll6
};
// const Cart_Item = Object.assign(xx, this.state.Cart_Item);
let yy = this.state.Cart_Item || [];
yy.push(xx);
this.setState({ Cart_Item: yy });
}
//else try to update object based on property value
// This is not working at all. it keeps on adding objects instead of updating
else {
for (var i in this.state.Cart_Item) {
if (this.state.Cart_Item[i].value === this.state.Select_Item) {
this.state.Cart_Item[i].Price = ll;
this.state.Cart_Item[i].Item = ll3;
this.state.Cart_Item[i].Quantity = this.state.Select_Quantity;
this.state.Cart_Item[i].Total_Item_Price = ll6;
// }
break; //Stop this loop, we found it!
}
}
// i tried below logic as well but it didnt work
// this.setState({
// Cart_Item:this.state.Cart_Item.filter(v => v.this.state.Select_Item.includes(this.state.Item))
// .concat([ xx ])
// });
}
console.log(this.state.Cart_Item);
}