简体   繁体   中英

react-native : updating object's value using setState

I am trying to update object's value using setState

In my code I am trying to update Date to 2019-06-22 and also update other values such as {dots: [vacation, massage, workout], selected: true} .

My Code:

this.setState(({pressedDate}) => ({
  pressedDate: {
     ...pressedDate,
      Date:'2019-06-22', :
      {
        dots: [vacation, massage, workout], selected: true
      }
   },
  }))

This will give me an error. I think my code is okay but don't know what is wrong.

Any advise or comments would be really appreciated! Thanks in advance!

Thanks @bkm412 I have the solution:

const newDate = '2019-06-22'
   this.setState(({pressedDate}) => ({
     pressedDate: {
     ...pressedDate,
      [newDate] :
      {
        dots: [vacation, massage, workout], selected: true
      }
   },
  }))
this.setState(({pressedDate}) => ({
  pressedDate: {
     ...pressedDate,
      ['2019-06-22'] :
      {
        dots: [vacation, massage, workout], selected: true
      }
   },
  }))

If you want to use variable


const newDate = 'any date';
this.setState(({pressedDate}) => ({
  pressedDate: {
     ...pressedDate,
      [newDate] :
      {
        dots: [vacation, massage, workout], selected: true
      }
   },
  }))

You want update Date to 2019-06-22 is okay, But I don't know what you to update into {dots: [vacation, massage, workout], selected: true} , He has no key.

You can try below code:

this.setState(({pressedDate}) => ({
  pressedDate: {
     ...pressedDate,
     Date:'2019-06-22',
     dots: [vacation, massage, workout],
     selected: true,
  },
}));

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