我有这样的默认状态:
this.state = {
location:{
lat: 1234,
lng: 3245
}
}
所以每次我想更新纬度或经度时我都必须这样做
this.setState({ location: {...this.state.location, lat: newLate} })
或
this.setState({ location: {...this.state.location, lng: newLng } })
如果我的组件中有多个 setState,我必须编写很多 ...
,如果我要使用一层嵌套对象,情况会更糟。此外,这样做很危险 {this.state.location.lat}
因为它会出错,如果未定义位置,它会使整个应用程序崩溃。当您在 React 中处理多个嵌套的对象数组或对象时,有什么提示?
最佳答案
只要有可能,尽可能保持状态“平坦”。
在你的情况下,你可以简单地做:
this.state = {
lat: 1234,
lng: 3245
}
随着你的状态变大,使用命名来隔离不同的属性
this.state = {
locationLat: 1234,
locationLng: 3245
}
即使在具有数百个组件的应用程序中,我也永远不需要使用嵌套状态。
补充说明:
- 每当看到这种模式时,将您的组件拆分成更小的部分
- 如果您知道每次都会更新整个对象,则只使用嵌套对象
从您的位置对象:
const location = {
lat: 1234,
lng: 3245
}
像这样初始化你的状态:
this.state = location
关于javascript - setState嵌套对象使用es6 spread,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48415251/