这是一个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"}}}
答案 0 :(得分:0)
使用点差运算符,您可以执行以下操作:
const updatedPeople = {
byID: {
...people.byID,
dan: {
...people.byID.dan,
age: 20,
sex: "male"
}
}
};
如果你需要id是动态的,使用计算属性键(另一个ES6特性,解构的一部分):
const id = 'dan';
const updatedPeople = {
byID: {
...people.byID,
[id]: {
...people.byID[id],
age: 20,
sex: "male"
}
}
};
这些解决方案是不变的完全证明,但是,如果您不熟悉ES6语法,它们可能很难阅读,如果您有更复杂的数据,您可以考虑使用immutablejs(或某种不可变库)< / p>