【问题标题】:nextjs - shopping cart problem with accurate cart total amountnextjs - 购物车总金额准确的购物车问题
【发布时间】:2021-02-20 10:04:56
【问题描述】:

我正在构建一个购物车,但对购物车的总金额有疑问。 当我进入购物车页面时,总金额仅显示添加到购物车的最后一件商品的数量。

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

【问题讨论】:

    标签: javascript reactjs next.js shopping-cart


    【解决方案1】:

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

    例子:

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

    【讨论】:

    • 使用 localStorage 而不是 cookie 来保存此类数据。
    猜你喜欢
    • 1970-01-01
    • 2013-06-29
    • 2013-11-22
    • 1970-01-01
    • 1970-01-01
    • 2017-04-28
    • 2011-08-01
    相关资源
    最近更新 更多