简体   繁体   中英

ReactJs how can i add object to array without mutating?

İn react , Let's say one checkbox is selected and message information is received. I am sending this information to array with setState and I can use this information. What I want is when I click on the second checkbox, I can still get this information, but when I send it to the array, the first selected array is deleted from the array, so I can only see the last one I selected. I want to add all of the ones I chose.

-- Lets say checkbox1 and checkbox 2 its clicked and take the data inside of them.

I dont want to do this => allMessage = [{id:1 , name"xyz"}]
I want this => allMessage =[{id:1, name:"xyz"} , {id:2, name:"zlk"}]

static calculateState(prevState, props) {
  return {
    selectedMessage: []
  }
}

handleCheckbox() {
  const { message } = this.props;

  const values = {
    id: message.rid,
    name: message.date
  }
  this.setState((prevState) => ({
    selectedMessage: [values, ...prevState.selectedMessage]
  }));

}

在此处输入图片说明

you can use the spread operator:

let array1 = [{name: "oguzhan bay"}]
let array2 = [..array1, {name: "5alidshammout"}]

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