2017-04-27 21 views
0

所以我有以下对象结构:如何更新React.js的状态对象中的单个属性的值?

const SamplePalette = { 
    id: 1, 
    name: "Sample Palette", 
    description: "this is a short description", 
    swatches: [ 
    { 
     val: "#FF6245", 
     tints: ["#FFE0DB", "#FFA797"], 
     shades: ["#751408", "#C33F27"] 
    }, 
    { 
     val: "#FFFDA4", 
     tints: ["#FFFFE1"], 
     shades: ["#CCCB83"] 
    }, 
    { 
     val: "#BFE8A3", 
     tints: ["#E7FFD7"], 
     shades: ["#95B77E"] 
    } 
    ] 
} 

让我们想象一下,这个目的是通过我的应用程序是这样的状态管理:

this.state = { 
    currentPalette: SamplePalette, 
} 

我的问题是如何将我去更新所述swatches阵列中一个给定的样本对象的属性val?或者更一般地说 - 我如何只更新这个对象的片断?

我尝试使用update帮手以及弄清Object.assign()是如何工作的,但是我一直不成功,坦率地说,仅仅通过查看示例就无法真正掌握语法。

而且,因为我将要修改这个对象相当多,我应该考虑使用也许终极版?

[编辑]

我试图@ maxim.sh建议,但没有成功:

this.setState(
    { currentPalette: {...this.state.currentPalette, 
     swatches[0].val: newValue} 
     }) 

回答

0

考虑你有新new_swatches

我觉得更清晰的方式是让阵列,更新和恢复成:

let new_swatches = this.state.currentPalette.swatches; 
new_swatches[0].val = newValue; 
this.setState(
     { currentPalette: 
      { ...this.state.currentPalette, swatches: new_swatches } 
}); 

还你:Immutability Helpershttps://github.com/kolodny/immutability-helper

可用命令

{$push: array} push() all the items in array on the target. 
{$unshift: array} unshift() all the items in array on the target. 
{$splice: array of arrays} for each item in arrays call splice() on the target with the parameters provided by the item. 
{$set: any} replace the target entirely. 
{$merge: object} merge the keys of object with the target. 
{$apply: function} passes in the current value to the function and updates it with the new returned value. 

+0

嘿!感谢您投入!那么更新更深层嵌套的属性呢?例如swatches数组中包含的对象的'val'属性。我想是这样的,但当然它没有工作...'this.setState({currentPalette:{... this.state.currentPalette,色板[0] .VAL:NEWVALUE}})' –

相关问题