简体   繁体   中英

How to add the same products to the cart with counter?

I want that when adding products to the basket it is not duplicated. but that would be written that the basket already has 2 or more of these goods. How do I implement this in code? I understand that I need a counter for added products but don't know how to do it. Please give me a tip I will be glad of any help.

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

This will leave you with a representation of your cart as { 1: n, 2: n, .... } where n is how many

You're only adding the product object once if its id isn't found in count. This is why q isn't changing; it's always 1 because that's what q is when it's added. You need to increment it if it is found in count. Leaving as much as your other code intact as possible:

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

Then to generate the total, you need to add the product of quantity * price, rather than just adding the price. In render():

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

Example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM