我正在尝试setState
,但我不知道如何解构具有动态属性名称的对象的其余部分。在此示例中,id
是表单中每个输入的动态值。
计算状态后,它看起来像这样:
{
"inputConfig": {
"5d4d684cadf8750f7077c739": {
"0": "5d4d684cadf8750f7077c739",
"isEmpty": true
},
"5d4d684cadf8750f7077c73c": {
"time": "2019-08-10T12:33:42.439Z",
"units": "f",
"defaultValue": 6,
"name": "Temp",
"isEmpty": true
}
}
}
动态 ID 包含具有输入配置的对象:
"5d4d684cadf8750f7077c73c": {
"time": "2019-08-10T12:33:42.439Z",
"units": "f",
"defaultValue": 6,
"name": "Temp",
"isEmpty": true
}
这是我到目前为止尝试过的代码:
this.setState(prevState => ({
...prevState,
inputConfig: {
...inputConfig,
[id]: {
...[id], // gives me {0: "5d4d684cadf8750f7077c739"} instead of the object it holds
}
}}),() =>{
console.log(this.state.inputConfig)
})
我想解构此 id
所持有的对象。有办法做到吗?
我很感谢对此的任何建议。
最佳答案
您需要引用特定 id 处的对象
let obj = {
"inputConfig": {
"5d4d684cadf8750f7077c739": {
"0": "5d4d684cadf8750f7077c739",
"isEmpty": true
},
"5d4d684cadf8750f7077c73c": {
"time": "2019-08-10T12:33:42.439Z",
"units": "f",
"defaultValue": 6,
"name": "Temp",
"isEmpty": false
}
}
}
let id = "5d4d684cadf8750f7077c73c"
let changed = {
inputConfig:{
...obj.inputConfig,
[id]:{
...obj.inputConfig[id],
isEmpty: true
}
}
}
console.log(changed)
关于javascript - 使用计算对象属性名称进行嵌套对象解构 - react 状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57447416/