简体   繁体   English

如何在按钮单击 Reactjs 上增加项目?

[英]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下面是用 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:是的,您可以看到 state 变量,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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