[英]Adding the function to remove products from the cart won't allow me to add more products
我有這個 function 來添加產品和他們的 colors,但是,一旦我添加了刪除產品和他們的 colors 的功能,它就不允許我再添加產品了。
我怎樣才能解決這個問題? 謝謝
代碼沙盒: https://codesandbox.io/s/add-to-cart-sampled-2-efqrhd?file=/src/App.js
代碼: App.js
export default function App() {
const [cartItems, setCartItems] = useState([]);
const [searchList, setSearchList] = useState([]);
const [searchKey, setSearchKey] = useState("");
useEffect(() => {
let x = [...products];
x = x.filter((y) => {
return y.prodName
.toLocaleLowerCase()
.includes(searchKey.toLocaleLowerCase());
});
setSearchList(x);
}, [searchKey]);
const handleAdd = (id, name, price, size, cat, color) => {
console.log("add", id, name, price, size, cat, color);
const productExist = cartItems.find(
(item) => item.id === id && item.color === color
);
if (productExist) {
setCartItems(
cartItems.map((item) =>
item.id === id && item.color === color
? { ...productExist, quantity: productExist.quantity + 1 }
: item
)
);
} else {
setCartItems([
...cartItems,
{ id, name, price, size, cat, color, quantity: 1 }
]);
}
};
const handleRemove = (product) => {
console.log(product, "remove");
const ProductExist = cartItems.find(
(item) => item.id === product.id && item.color === product.color
);
if (ProductExist.quantity === 1) {
setCartItems(cartItems.filter((item) => item.id !== product.id));
} else {
setCartItems(
cartItems.map((item) =>
item.id === product.id && item.color === product.color
? { ...ProductExist, quantity: ProductExist.quantity - 1 }
: item
)
);
}
};
const handleCartClearance = () => {
setCartItems([]);
};
console.log(cartItems);
return (
<div className="App">
<div>
<input
placeholder="Search product..."
value={searchKey}
onChange={(e) => setSearchKey(e.target.value)}
/>
{searchList.map((item, index) => (
<ul key={item.id}>
<li>
<b>{item.prodName}</b>
</li>
<li>Category: {item.cat}</li>
<li>Size: {item.size}</li>
<li>Php {item.price}.00</li>
{Object.entries(item.colorMap).map((color) => (
<>
{color[1] !== 0 ? (
<>
{color[0]}
<button
onClick={(e) =>
handleAdd(
item.id,
item.prodName,
item.price,
item.size,
item.cat,
color[0]
)
}
>
Add
</button>
{/* <button onClick={(e) => handleAdd(index)}>Add to Cart</button> */}
</>
) : (
<>2</>
)}
<br />
</>
))}
</ul>
))}
</div>
<Cart
cartItems={cartItems}
handleCartClearance={handleCartClearance}
handleRemove={handleRemove}
handleAdd={handleAdd}
/>
</div>
);
}
購物車.js
const Cart = ({ cartItems, handleCartClearance, handleRemove, handleAdd }) => {
console.log(cartItems, "items");
const totalAmount = cartItems.reduce(
(price, item) => price + item.quantity * item.price,
0
);
return (
<div>
Cart page
{cartItems.length >= 1 && (
<button onClick={handleCartClearance}>Clear Orders</button>
)}
{cartItems.length === 0 && <div>No Items in the cart</div>}
<div>
{cartItems.map((item) => (
<div key={item.id}>
<li>{item.id}</li>
<li>{item.name + " " + item.size + "" + item.cat}</li>
<li>{item.color}</li>
<li>{item.quantity}</li>
<li>Total: {parseInt(item.quantity) * parseInt(item.price)}</li>
<button
onClick={(e) =>
handleAdd(
item.id,
item.prodName,
item.price,
item.size,
item.cat,
item.color
)
}
>
+
</button>
<button onClick={handleRemove(item)}>- </button>
</div>
))}
<div>
<b>Total Amount :{totalAmount}</b>
</div>
</div>
</div>
);
};
export default Cart;
我想你應該 go 簡單到復雜。 據我了解,你有(1)UserInput(即searchKey)
(2)列表(即SearchList)
(3) 購物車(即cartItems)。
你需要2個功能。
(1). 添加到購物車(項目)
(2). 從購物車中移除(項目)
function addToCart(item){
//check item already exists or not
//if exists, return
//if not addToCart
}
function removeFromCart(item){
//check item exists in cart
//if not, return
//if exists, removeFromCart
}
您有 arrays 個對象。 使用 filter() 很容易檢查項目是否存在。
const List = [{id: 0, name: 'a'},{id: 1, name: 'b'},...];
function addToCart(item){
const alreadyExist = List.filter(listItem=> listItem.id === item.id).length > 0;
if (alreadyExist) return;
//else execute the rest of the function
//I used spread iterator
setCartItems([...cartItems, item]);
}
function removeFromCart(item){
//these codes not even necessary
//const alreadyExist = cartItems.filter(cartItem=> cartItem.id === item.id).length > 0;
//if (!alreadyExist) return;
setCartITems(cartItems.filter(cartItem=> cartItem.id !== item.id);
}
我的意思是,先構建簡單的函數,然后再構建復雜的 go。 然后,您就會知道錯誤發生在哪里。 當屏幕上沒有顯示錯誤時,有一種調試方法。 console.log()
。 它可以顯示您在 function 期間變量的值。例如,
function addToCart(item){
console.log('Before adding CartItems is ', cartItems);
const alreadyExist = List.filter(listItem=> listItem.id === item.id).length > 0;
console.log('CartItem already Exist?', alreadyExist);
if (alreadyExist) return;
//else execute the rest of the function
//I used spread iterator
setCartItems([...cartItems, item]);
console.log(item, ' new item was added to CartItems');
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.