简体   繁体   中英

setState nested object using es6 spread

I have default state like this:

this.state = {
  location:{
    lat: 1234,
    lng: 3245
  }
}

so every time I want to update either lat or lng I have to do this

this.setState({ location: {...this.state.location, lat: newLate} })

or

this.setState({ location: {...this.state.location, lng: newLng } })

if I have several setState in my component I have to write a lot of ... , worse if I have one level of nested object to work with. Also it's dangerous to do this {this.state.location.lat} because it will have error and it make the whole app to crash if location is not defined. What's the tip when you work on multiple nested array of object or object in react?

Whenever possible, keep your state as 'flat' as possible.

In your case, you can simply do:

this.state = {
  lat: 1234,
  lng: 3245
}

As your state becomes bigger, use naming to segregate the different properties

this.state = {
  locationLat: 1234,
  locationLng: 3245
}

Even in applications with hundreds of components, I never need to use nested states.

Additional remarks:

  • Split your component into smaller pieces whenever you see this pattern
  • Only use a nested object if you know the entire object will be updated each time

From your location object:

const location = {
    lat: 1234,
    lng: 3245
}

initialize your state like so:

this.state = location

It is always recommended to keep the state flat as possible. So In your case it can be

state={
  locationLat:123,
  locationLng: 456,
}

The main reason of it comes from How object.assign works . It copy the value for only first level.

See the native implementation of Object.assign to understand more. Since it copy only for first level it is recommended to keep state flat.

 var a = {b:1, c:{d:1}} var e = Object.assign({},a) console.log(a===e) // It will false ecd = 2 console.log(acd) //It will be 2 

Ref to Read more:

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