这是一个 babel/ES7 问题(供 redux reducer 使用)
我只想在某些属性中更新“dan”。不变性思维的首选方式是什么?
似乎只有 TRY 1 和 TRY 3 正确合并/更新。
两者有什么区别吗?对我来说,TRY 3 获胜,因为它是最短的(如果 TRY 1 没有区别)
谢谢
const people = { byID: {
gaston : { name:'Gaston', age: 22 },
dan : { name: 'gaston', age: 44 }
}
}
const currentID = "dan"
///
// TRY 1
const thisID = {}
thisID[currentID] = {...people.byID[currentID],
age: 20,
sex: 'male',
}
const newPeople = {...people,
byID: {...people.byID,
...thisID
}
}
console.log( newPeople ) // OK
//
// TRY 2
const newPeople2 = {}
newPeople2.byID = {}
newPeople2.byID[currentID] = {}
newPeople2.byID[currentID]["age"] = 20
newPeople2.byID[currentID]["sex"] = "male"
const newPeople3 = {...people, ...newPeople2}
console.log( newPeople3 ) // NOPE (not merge)
//
// TRY 3
const newPeople4 = {...people}
newPeople4.byID = newPeople4.byID || {}
newPeople4.byID[currentID] = newPeople4.byID[currentID] || {}
newPeople4.byID[currentID]["age"] = 20
newPeople4.byID[currentID]["sex"] = "male"
console.log(newPeople4) // OK
这是输出
TRY 1
{"byID":{"gaston":{"name":"Gaston","age":22},"dan":{"name":"gaston","age":20,"sex":"male"}}}
TRY 2
{"byID":{"dan":{"age":20,"sex":"male"}}}
TRY 3
{"byID":{"gaston":{"name":"Gaston","age":22},"dan":{"name":"gaston","age":20,"sex":"male"}}}