[英]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 構建的購物車。 購物車在 1 之后不顯示購物車中的商品總數。即 1 是它可以計算的最大數量。 我希望它計數超過 1 個項目。 這是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>
);
}
}
應用程序.js
我也包含了 state
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 上代碼的鏈接:鏈接到 Github
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}] });
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.