【问题标题】:I have built a shopping cart using React. Why isn't my cart working? By working I mean why isn't the count in the cart increasing?我已经使用 React 构建了一个购物车。为什么我的购物车不工作?通过工作,我的意思是为什么购物车中的数量没有增加?
【发布时间】:2021-06-10 14:19:41
【问题描述】:

我使用 React 构建了一个购物车。购物车在 1 之后不显示购物车中的商品总数。即 1 是它可以计算的最大数量。我希望它计数超过 1 个项目。这是Cart 组件:

Cart.js

    import React, { Component } from 'react'
    import formatCurrency from '../util';


    export default class Cart extends Component {
    render() {
        const { cartItems } = this.props;
        //this part is not displaying the number of items in the cart
        return (
            <div>
                {cartItems.length === 0 ? (
          <div className="cart cart-header">Cart is empty</div>
        ) : (
          <div className="cart cart-header">
            You have {cartItems.length} in the cart{" "}
          </div>
        )}

                <div>
                <div className="cart">
                    <ul className="cart-items">
                        {cartItems.map(item => (
                            <li key={item._id}>
                                <div>
                                     <img src={item.image} alt={cartItems.title}></img>
                                </div>
                                <div>
                                    <div>{item.title}</div>
                                    <div className="right">
                                    {formatCurrency(item.price)} * {item.count}
                                        <button onClick={ () => this.props.removeFromCart(item)}>         Remove</button>
                                    </div>
                                    
                                </div>
                            </li>
                        ) )}
                    </ul>

                </div>
            </div>

            </div>
            
           
        );
    }
} 

App.js

我也加入了状态

    class App extends React.Component {
    constructor(){
    super();
    this.state = {
      products: data.products,
      cartItems: [],
      size:"",
      sort:"",
    };
  }

    //this part is not working

    addToCart = (product) => {
    const cartItems = this.state.cartItems.slice();
    let alreadyInCart = false;
    cartItems.forEach((item) => {
      if (item._id === product._id) {
        item.count++;
        alreadyInCart = true;
      }
    });
    if (!alreadyInCart) {
      cartItems.push({...product, count: 1 });
    }
    this.setState({cartItems});
    };

这里是 Github 上的代码链接:Link To Github

【问题讨论】:

  • 当您尝试将产品添加到购物车时会发生什么?
  • 用map代替forEach,增加count后返回item

标签: javascript reactjs shopping-cart


【解决方案1】:
addToCart = (product) => {
  const { cartItems } = this.state;
  // find whether the product is there in the cartItems
  const isProductPresent = cartItems.some(item => item.id === product.id);
  if(isProductPresent){
    const updatedCartItems = cartItems.map(item => {
      if(item.id === product.id){
        return { ...item, count: ++item.count}
      }
      return item;
    })
    this.setState({cartItems: updatedCartItems});
  }
  else {
    this.setState({cartItems: [...cartItems, {...product, count: 1}] });
  }
  };

【讨论】:

  • 这与原始代码没有什么不同。购物车中的计数不超过 1
  • 那么你也应该在 cartItem 中添加对象的形状。
  • 从您的问题中不清楚您所说的count 是什么意思-您是指单个项目s count or the cartItems.length` 吗?
  • @Augustin 我下载了你的代码并在我的本地运行,看起来有错字:-)。您的 item 中没有 _id 属性。它只是 id 。将您的代码更改为此 if (item.id === product.id) { 。它应该可以正常工作:-)
  • 此外,在检查您的代码时,我可以看到三个 ID 为 van3 的产品。因此,您需要将一些唯一值传递给id,否则如果您尝试将所有 6 件商品添加到购物车中,则只会添加 4 件,因为只有 4 个唯一 ID。尝试将所有 6 件商品添加到购物车。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多