【问题标题】:What's the difference and/or preferred way of updating a deep property?更新深层属性的区别和/或首选方式是什么?
【发布时间】:2016-01-16 10:53:39
【问题描述】:

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

【问题讨论】:

    标签: babeljs redux ecmascript-2016


    【解决方案1】:

    使用展开运算符,您可以:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-16
      • 2019-06-20
      • 2022-01-03
      • 1970-01-01
      • 2011-11-14
      • 2010-09-12
      • 1970-01-01
      相关资源
      最近更新 更多