【问题标题】:How to update the value of a single property within a state object in React.js?如何更新 React.js 中状态对象中单个属性的值?
【发布时间】:2017-04-27 12:00:45
【问题描述】:

所以我有以下对象结构:

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() 的工作原理,但是我没有成功,坦率地说,仅通过查看示例无法真正掌握语法。

另外,由于我要大量修改这个对象,我应该考虑使用 Redux 吗?

[编辑]

我尝试了@maxim.sh 的建议,但没有成功:

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

【问题讨论】:

    标签: javascript reactjs state


    【解决方案1】:

    假设你有新的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.
    

    【讨论】:

    • 嘿!感谢您的投稿!那么更新一个更深的嵌套属性呢?例如,样本数组中包含的对象的val 属性。我试过这样的东西,但当然它没有用......this.setState({ currentPalette: {...this.state.currentPalette, swatches[0].val: newValue}})
    猜你喜欢
    • 1970-01-01
    • 2019-12-15
    • 2020-03-05
    • 2020-06-14
    • 1970-01-01
    • 2020-04-27
    • 2021-12-02
    • 2019-12-07
    • 2020-05-02
    相关资源
    最近更新 更多