简体   繁体   English

如何使用 reactjs 将多个项目添加到数组

[英]How to add multiple items to array with reactjs

I have two classes.我有两节课。 One holds the array, the other holds the array props.一个持有数组,另一个持有数组道具。 These are my classes:这些是我的课:

//PARENT CLASS: //父 CLASS:

constructor() {
   super()

   this.state = {
      items: []
   }

   this.addItem = this.addItem.bind(this)
}

componentDidMount(){
   this.setState({
      items: [{
         name: 'Sebastian',
         num: '001'
      },{
         name: 'Josh',
         num: '002'
      }]
   })
}

addItem() {
??????
}

render() {
   return(
      <div>
        <MethodA items={this.state.items} addItem={this.addItem}/>
      </div>
   )
}

//CHILD CLASS: //孩子 CLASS:

function MethodA(props) {
   return(
      <div>
         {props.items.map((item, i) =>{
            return(<div key={i}>
               <span>{item.name}</span>
               <span>{item.num}</span>
            </div>)
         })}

         <button onClick={() => { props.addItem() }}>ADD ITEM</button>
      </div>
   )
}

Current result is like this:目前的结果是这样的:

<div>
   <span>Sebastian</span>
   <span>001</span>
</div>
<div>
   <span>Sebastian</span>
   <span>002</span>
</div>

Then after the "ADD ITEM" button was hit, this will be the new result:然后在“添加项目”按钮被点击后,这将是新的结果:

<div>
   <span>Sebastian</span>
   <span>001</span>
</div>
<div>
   <span>Sebastian</span>
   <span>002</span>
</div>
<div>
   <span>New Name</span>
   <span>New Num</span>
</div>

I'm not sure whether what and how to use between push() or concat() or both.我不确定在 push() 或 concat() 或两者之间是否使用什么以及如何使用。 Any ideas?有任何想法吗?

Firstly, there's no need to set the initial state in componentDidMount , you can do it directly in constructor.首先,不需要在componentDidMount中设置初始的 state ,可以直接在构造函数中设置。

constructor(props) {
    super(props);

    this.state = {
      items: [
        {
          name: "Sebastian",
          num: "001"
        },
        {
          name: "Josh",
          num: "002"
        }
      ]
    };

    this.addItem = this.addItem.bind(this);
  }

To add an item you can use functional form of setState and you'll need to pass that item into callback from the child component.要添加一个项目,您可以使用setState的函数形式,并且您需要将该项目传递给子组件的回调。

addItem(item) {
    this.setState(state => ({
      items: [...state.items, item]
    }));
  }

// Child class
function MethodA(props) {
   return(
      <div>
         {props.items.map((item, i) =>{
            return(<div key={i}>
               <span>{item.name}</span>
               <span>{item.num}</span>
            </div>)
         })}

         <button onClick={() => props.addItem(item)}>ADD ITEM</button> // Pass item to the parent's method
      </div>
   )
}

Here's the deal.这是交易。 The difference between push() and concat() is in immutability. push() 和 concat() 之间的区别在于不变性。

If you use push on an array, it will mutate the original array and add a new value to that array (wrong).如果您在数组上使用 push,它将改变原始数组并向该数组添加一个新值(错误)。

If you use concat, it will create a new array for you, leaving the old array untouched (correct).如果您使用 concat,它将为您创建一个新数组,而旧数组保持不变(正确)。

So you might want to do something along these lines:因此,您可能想要按照以下方式做一些事情:

addItem(item)
  this.setState(state => {
    const items = state.items.concat(item);
    return {
      items,
    };
  });
}

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

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