【问题标题】:Update Multiple Properties of an object with spread operator使用扩展运算符更新对象的多个属性
【发布时间】:2017-06-12 04:51:10
【问题描述】:

我在减速器中有一个如下所示的状态:

// The current source/selection
const selection = {
  timespan: "-3660",
  customTimespan: false,
  pathIds: [''],
  source: undefined,
  direction: 0,
  appClassIds: []
};

我现在想要更新多个属性(timespan 和 customTimeSpan),类似这样(但这不起作用):

{ ...state, 
  {
      timespan: action.timespan.value,
      customTimespan: action.timespan.value
  } 
};

如何更新一个状态的多个属性?

【问题讨论】:

  • 这样使用 Object.assign({},state,{ timespan: action.timespan.value, customTimespan: action.timespan.value } );
  • 你在里面多了一层嵌套。

标签: javascript reactjs redux react-redux


【解决方案1】:

你需要从那里移除额外的对象闭包

{ ...state, 
 timespan: action.timespan.value, 
 customTimespan: action.timespan.value
}

应该可以正常使用

如果你想在原版 JS 中这样做,你可以这样做:

Object.assign({}, state, { timespan: action.timespan.value, customTimespan: action.timespan.value})

我认为价差运算符要干净得多,如果您可以访问它,应该走那条路。

【讨论】:

    【解决方案2】:

    您也可以使用扩展运算符实现相同的目的,它允许您在对象中拥有新值,而不必对它们进行硬编码:

    const selection = {
      timespan: "-3660",
      customTimespan: false,
      pathIds: [""],
      source: undefined,
      direction: 0,
      appClassIds: []
    };
    
    const newSelectionValues = {
      timespan: "-3600",
      customTimespan: true
    };
    
    const newSelection = { ...selection, ...newSelectionValues };
    

    【讨论】:

    • 您可以通过扩展运算符更新selection 对象,而不是创建newSelection 吗?我想不出合适的语法,但它会很有用。
    猜你喜欢
    • 2018-09-04
    • 2017-06-12
    • 2020-03-18
    • 2017-06-13
    • 2021-12-28
    • 2017-11-15
    • 1970-01-01
    • 2018-05-13
    相关资源
    最近更新 更多