[英]How to add the same products to the cart with counter?
我希望在將產品添加到購物籃時不會重復。 但那會寫成籃子里已經有 2 個或更多這樣的商品。 如何在代碼中實現這一點? 我知道我需要一個添加產品的櫃台,但不知道該怎么做。 請給我一個提示,我會很高興得到任何幫助。
import React from "react";
import ReactDOM from "react-dom";
class Shop extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [
{
id: 1,
name: "Product 1",
price: "50",
q:0
},
{
id: 2,
name: "Product 2",
price: "70",
q:0
},
{
id: 3,
name: "Product 3",
price: "80",
q:0
},
{
id: 4,
name: "Product 4",
price: "90",
q:0
},
{
id: 5,
name: "Product 5",
price: "100",
q:0
}
],
count: []
};
}
incrementCount = (item) => {
const {id, name, price, q} = item;
let array = [...this.state.count];
let indexOfStevie = array.findIndex(i => i.id === id);
array[indexOfStevie] = {...item, q: q+1}
console.log(array[indexOfStevie])
if (!array.some(i => i.id === id)) {
this.setState({
count: [...this.state.count, { id, name, price, q: q+1}]
});
}
};
delete = id => {
let array = [...this.state.count].filter(item => item.id !== id);
this.setState({
count: [...array]
});
};
render() {
return (
<div className="wrap">
<div>
<h3>products</h3>
<ul>
{this.state.data.map(item => (
<li key={item.id}>
{item.name}
{item.price}
<button
onClick={() =>
this.incrementCount(item)
}
>
add
</button>
</li>
))}
</ul>
</div>
<div>
<h3>bascket</h3>
<ul>
{this.state.count.map(item => (
<li>
{item.id}
{item.name}
<button onClick={() => this.delete(item.id)}>X</button>
</li>
))}
</ul>
<div>
{this.state.count.length == 0
? "empty"
: "total" +
this.state.count.reduce(
(accumulator, currentValue) =>
accumulator + +currentValue.price,
0
)}
</div>
</div>
</div>
);
}
}
ReactDOM.render(<Shop />, document.getElementById("todos-example"));
constrsuctor(props){
this.state = { my_cart : {} }
}
add_to_cart = (item) => {
let cart_instance = this.state.my_cart[item.id];
this.setState({
my_cart : { ...this.state.my_cart, [item.id] : (cart_instance) ? this.state[item.id] + 1 : 0 }
});
}
這將使您的購物車表示為 { 1: n, 2: n, .... } 其中 n 是多少
如果在計數中找不到產品 object ,您只需添加一次產品 id。 這就是為什么 q 沒有改變; 它始終為 1,因為這就是 q 添加時的含義。 如果在計數中找到它,則需要增加它。 盡可能多地保留其他代碼:
incrementCount = (item) => {
const {id, name, price, q} = item;
let array = [...this.state.count];
let indexOfStevie = array.findIndex(i => i.id === id);
// if the product is currently in the count, modify it
if(indexOfStevie > -1) {
array[indexOfStevie].q++
this.setState( {
count: array
} );
} else {
// the product is not currently in count, add it
this.setState({
count: [...this.state.count, { id, name, price, q: q+1}]
});
}
};
然后要生成總數,您需要添加數量*價格的乘積,而不是僅添加價格。 在渲染()中:
{this.state.count.length == 0
? "empty"
: "total" +
this.state.count.reduce(
(accumulator, currentValue) =>
// add the product of quantity and price to total
accumulator + (currentValue.q * currentValue.price),
0
)}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.