簡體   English   中英

在狀態數組中添加對象

[英]Adding object inside state's array

我正在嘗試在狀態中定義的數組中添加一個對象,該(對象)我從一個孩子那里得到然后向上移動到父母,將其設置為父母的狀態並將其提供給另一個(孩子的代碼在下面)孩子作為道具。 我看到了一些解決方案,但它們不起作用。 目前的解決方案給了我一個無限循環,一遍又一遍地添加道具項目。 所以我的問題是如何在狀態中定義的數組中添加一個項目,而我們得到的項目是一個道具。 這是我的代碼

import React, { Component } from "react";

import "./ShoppingCart.css";



class ShoppingCart extends Component {
  constructor(props) {
    super(props);
    
    this.state = {
      items: [],
    };
  }


  

  onAddItem = () => {

    if(Object.keys(this.props.item).length !== 0)
    //checking initial empty prop
    {

      const item = this.props.item;
      //an object consist of {id,title,price...etc}
      
      //the solution i found on the internet
      const newList = this.state.items.concat(item);
      console.log("New List",newList);
  
      this.setState({
        items:newList
      })

    }


  };

  render() {
    this.onAddItem();
    return (
      <React.Fragment>
        <button className="cart-button">
          <img className="shopping-cart-img" src="./images/shopping-cart.png" />
          {/* Here will be some code*/}
        </button>
      </React.Fragment>
    );
  }
}

export default ShoppingCart;

您在每次渲染時調用該函數,然后設置狀態,導致另一個渲染,然后渲染再次調用該函數......這是一個無限循環。

  render() {
    this.onAddItem(); // ❌ REMOVE THIS LINE
    return (
      <React.Fragment>
        <button className="cart-button" onClick={this.onAddItem}> //✅ add onclick event to add item here
          <img className="shopping-cart-img" src="./images/shopping-cart.png" />
          {/* Here will be some code*/}
        </button>
      </React.Fragment>
    );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM