简体   繁体   中英

SetState in an array with React spread operator

I have a value in my react state that looks like so:

appointmentsData = {
  "05-01-2018": [
    {
      id: "1",
      friendly: "9:00am - 10:00am",
      openDateTime: "9:00am",
      closeDateTime: "10:00am"
    }
  ]
};

I have a new piece of data:

const newAppt = {"06-30-2018":[]}

How do I addon to my data in the state? I tried

this.setState({ ...this.state.appointmentsData, ...newAppt}); 

It seems to no be adding onto state though. I get back the same value in the render as before (appointmentData before spread). The newAppt never gets added to the state.

I am trying to get my states desired output to be:

appointmentsData = {
  "05-01-2018": [
    {
      id: "1",
      friendly: "9:00am - 10:00am",
      openDateTime: "9:00am",
      closeDateTime: "10:00am"
    }
  ],
  "06-30-2018": []
};

Many ways to do it, really. Here's one:

this.setState(prevState => (
  {appointmentsData: {...prevState.appointmentsData}, newAppt}
));

Though your approach should work too, if you just add the appointmentsData: first. Like so:

this.setState({appointmentsData: {...this.state.appointmentsData, ...newAppt}});

This will spread all the previous values into a new object, plus the one you want to add.

I personally always use the functional way of setting the state when the new one depends on a previous state value, but your way is fine here too.

You should not use spread operator on newAppt . Just go with: this.setState({ ...this.state.appointmentsData, newAppt}); . It seems to me that the spread operator on newAppt is not getting any data for the const .

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