简体   繁体   English

在状态数组中添加对象

[英]Adding object inside state's array

I'm trying to add an object in the array defined in the state, which (object) I get from a child then moving up to the parent, setting it to parent's state and giving it to another(that child's code is down below) child as a prop.我正在尝试在状态中定义的数组中添加一个对象,该(对象)我从一个孩子那里得到然后向上移动到父母,将其设置为父母的状态并将其提供给另一个(孩子的代码在下面)孩子作为道具。 I saw some solutions but they are not working.我看到了一些解决方案,但它们不起作用。 The present solution gives me an infinite loop, props item is added over and over.目前的解决方案给了我一个无限循环,一遍又一遍地添加道具项目。 So my question is how to add an item in the array which is defined in the state and the item that we are getting is a prop.所以我的问题是如何在状态中定义的数组中添加一个项目,而我们得到的项目是一个道具。 Here's my code这是我的代码

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;

You are calling the function on every render and then setting state, causing another render, and then the render call the function again.... it's an infinite loop.您在每次渲染时调用该函数,然后设置状态,导致另一个渲染,然后渲染再次调用该函数......这是一个无限循环。

  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