nextjs -购物车的问题与准确的购物车总额



我正在构建一个购物车,并且在购物车总金额方面存在困难。当我进入购物车页面时,总金额只显示最后添加到购物车中的商品的金额。

state = {
cart: { items: [], total: 0 },
};
addItem = (item) => {
let { items } = this.state.cart;
//check for item already in cart, if not found, increase quantity by 1
const itemFound = items.find((i) => i.id === item.id);
if (!itemFound) {
item.quantity = 1;
// console.log(this.state.cart.total, item.price);
this.setState(
{
cart: {
items: [...items, item],
total: this.state.cart.total + item.price,
},
},
() => Cookie.set("cart", this.state.cart.items)
);
} else {
this.setState(
{
cart: {
items: this.state.cart.items.map((item) =>
item.id === itemFound.id
? Object.assign({}, item, { quantity: item.quantity + 1 })
: item
),
total: this.state.cart.total + item.price,
},
},
() => Cookie.set("cart", this.state.cart.items)
);
}
};

我发现问题发生时,我手动导航到购物车页面例如:http://localhost:3000/cart

如果我通过"下一个链接"导航到购物车页面,它会显示正确的总数,但是在页面刷新时,它会再次显示添加到购物车中的最后一项的金额为总金额
下面是我如何检索购物车和设置状态

componentDidMount() {
const cart = Cookie.get("cart");
//if items in cart, set items and total from cookie
if (typeof cart === "string" && cart !== "undefined") {
JSON.parse(cart).forEach((item) => {
this.setState({
cart: { items: JSON.parse(cart), total: item.price * item.quantity },
});
});
}
}

我目前在cookie中存储购物车项目,而不是总
这种方法有问题,我无法弄清楚。期待指导谢谢你

在设置状态之前,您需要将商品的数量与该商品的相应价格相乘以得到总价。

的例子:

let total = this.state.cart.items.reduce(
(accumalatedQuantity, cartItem) =>
accumalatedQuantity + cartItem.quantity * cartItem.price,
0
)

最新更新