0

这是一个 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"}}}
4

1 回答 1

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(或某种不可变库)

于 2016-01-17T01:55:57.350 回答