简体   繁体   English

使用es6传播的setState嵌套对象

[英]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. 如果我的组件中有多个setState,我必须编写很多... ,如果我要使用一层嵌套的对象,那就更糟了。 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. 这样做{this.state.location.lat}也很危险,因为它将出错并且如果未定义位置,则会使整个应用程序崩溃。 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 . 其主要原因来自object.assign的工作方式 It copy the value for only first level. 它仅复制第一级的值。

See the native implementation of Object.assign to understand more. 请参阅Object.assign的本机实现以了解更多信息。 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: 参考阅读更多:

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

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