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

时间:2021-02-20 10:04:56

标签: javascript reactjs next.js shopping-cart

我正在构建一个购物车,但在处理购物车总金额时遇到困难。 当我转到购物车页面时,总金额仅显示添加到购物车的最后一件商品的数量。

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 中存储购物车项目,而不是全部
这种方法有问题,我无法弄清楚。 期待指导 谢谢

1 个答案:

答案 0 :(得分:0)

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

示例:

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