Javascript 如何将相同的产品添加到带计数器的购物车?

Javascript 如何将相同的产品添加到带计数器的购物车?,javascript,reactjs,Javascript,Reactjs,我希望在向篮子中添加产品时不要重复。但这会被写进篮子里已经有两种或更多的这种商品。 如何在代码中实现这一点? 我知道我需要一个柜台来处理添加的产品,但我不知道怎么做。 请给我一个小费,我会很高兴得到任何帮助 import React from "react"; import ReactDOM from "react-dom"; class Shop extends React.Component { constructor(props) { super(props); th

我希望在向篮子中添加产品时不要重复。但这会被写进篮子里已经有两种或更多的这种商品。 如何在代码中实现这一点? 我知道我需要一个柜台来处理添加的产品,但我不知道怎么做。 请给我一个小费,我会很高兴得到任何帮助

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"));
从“React”导入React;
从“react dom”导入react dom;
类。组件{
建造师(道具){
超级(道具);
此.state={
数据:[
{
id:1,
名称:“产品1”,
价格:“50”,
q:0
},
{
id:2,
名称:“产品2”,
价格:“70”,
q:0
},
{
id:3,
名称:“产品3”,
价格:“80”,
q:0
},
{
id:4,
名称:“产品4”,
价格:“90”,
q:0
},
{
id:5,
名称:“产品5”,
价格:“100”,
q:0
}
],
计数:[]
};
}
递增计数=(项目)=>{
const{id,name,price,q}=item;
让数组=[…this.state.count];
让indexOfStevie=array.findIndex(i=>i.id==id);
数组[indexOfStevie]={…项,q:q+1}
log(数组[indexOfStevie])
if(!array.some(i=>i.id==id)){
这是我的国家({
count:[…this.state.count,{id,name,price,q:q+1}]
});
}
};
删除=id=>{
让数组=[…this.state.count].filter(item=>item.id!==id);
这是我的国家({
计数:[……数组]
});
};
render(){
返回(
产品
    {this.state.data.map(项=>(
  • {item.name} {item.price} 此。递增计数(项) } > 添加
  • ))}
巴斯克
    {this.state.count.map(项=>(
  • {item.id} {item.name} this.delete(item.id)}>X
  • ))}
{this.state.count.length==0 “空的” :“总计”+ this.state.count.reduce( (累加器,当前值)=> 累加器++当前值.price, 0 )} ); } } render(,document.getElementById(“todos示例”);

这将为您的购物车留下一个表示形式{1:n,2:n,…..},其中n是数量

如果在计数中找不到产品对象的id,则只添加一次产品对象。这就是为什么q没有改变;它总是1,因为当它被添加时,这就是q。如果在count中找到它,则需要增加它。尽可能保留其他代码的完整性:

  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}]
      });
    }
  };
然后,要生成总数,您需要添加数量*价格的乘积,而不仅仅是添加价格。在render()中:

  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
     )}