简体   繁体   中英

How to increment item on button click Reactjs?

I am working on a demo shopping app. I have a cart component which fetches the cart items from local storage and displays the items in a table. I have given two buttons to the user for adding and removing items from the cart. When the user adds an item to the cart it gets updated in the local storage but does not reflect on the quantity displayed on the table, the quantity updates only when the page is rendered again. What is the best practice to solve this issue?

Below is the code written in Cart.js

   render() {
    const cartItems = JSON.parse(localStorage.getItem("cart"));
    console.log(cartItems)
    if (cartItems) {
      return (
          <div>
        <Table striped bordered hover size="sm">
          <thead>
            <tr>
              <th>Image</th>
              <th>Product Name</th>
              <th>Price per unit</th>
              <th>Quantity</th>
              <th>Total price</th>
            </tr>
          </thead>
          <tbody>
            {cartItems.map((item) => (
              <tr key={item.id}>
                <td>
                  <Image src={item.image} height="100px" width="auto"></Image>{" "}
                </td>
                <td>{item.name}</td>
                <td><i className="fa fa-inr"></i> {item.price}</td>
                <td>
                  {item.qty}
                  <br>
                  </br>
                  <button onClick={() => this.addToCart(item)} >
                  <i className="fa fa-plus"></i> 
                </button>
                  <button><i className="fa fa-minus"></i> </button>
                </td>
                <td>
                 <i className="fa fa-inr"></i> {item.qty * item.price}
                </td>
              </tr>
            ))}

          </tbody>
        </Table>
        </div>
      );
    } else {
      return (
        <div align="center">
          <h1>Add Items to your Cart ! ^_^ </h1>
          <br></br>
          <Button onClick={this.routeChange}>Go to Dashboard ! </Button>
        </div>
      );
    }
  }

Yes you can see the state variable for the same like below:

 this.state = {
          cartItems: []
        };

    addItem(item){
    this.setState({
      cartItems: [...this.state.cartItems, item]
    })

you can try something like this

 handleSubtractQuantity = (id)=>{
    this.props.subtractQuantity(id);
    this.forceUpdate()
}
    export default function Cart {
    const [cartItems, setCartItems] = useState([]);

    const handleAddition = (item) => {
        if (!cartItems.includes(item)) {
            setCartItems([...cartItems, item]);
         }
    }

    render() {
     return ( 
     cartItems && (
          <div>
        <Table striped bordered hover size="sm">
          <thead>
            <tr>
              <th>Image</th>
              <th>Product Name</th>
              <th>Price per unit</th>
              <th>Quantity</th>
              <th>Total price</th>
            </tr>
          </thead>
          <tbody>
            {cartItems.map((item) => (
              <tr key={item.id}>
                <td>
                  <Image src={item.image} height="100px" width="auto"></Image>{" "}
                </td>
                <td>{item.name}</td>
                <td><i className="fa fa-inr"></i> {item.price}</td>
                <td>
                  {item.qty}
                  <br>
                  </br>
                  <button onClick={() => this.addToCart(item)} >
                  <i className="fa fa-plus"></i> 
                </button>
                  <button><i className="fa fa-minus"></i> </button>
                </td>
                <td>
                 <i className="fa fa-inr"></i> {item.qty * item.price}
                </td>
              </tr>
            ))}

          </tbody>
        </Table>
        </div>
      );
    }
)
       <div align="center">
          <h1>Add Items to your Cart ! ^_^ </h1>
           <br></br>
           <Button onClick={this.routeChange}>Go to Dashboard ! </Button>
       </div>
      );
    }
  }
}

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