简体   繁体   English

使用传播算子更新对象的多个属性

[英]Update Multiple Properties of an object with spread operator

I have a state in a reducer that looks like this: 我在减速器中有一个看起来像这样的状态:

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

What I want now is to update multiple properties (timespan and customTimeSpan), something like this (but this doesn't work): 我现在想要的是更新多个属性(timespan和customTimeSpan),类似这样(但这不起作用):

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

How can I update multiple properties of a state? 如何更新状态的多个属性?

You need to remove the extra object closure from there 您需要从那里删除多余的对象封闭

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

should work fine 应该工作正常

If you wanted to do it in vanilla JS you could do this: 如果您想在Vanilla JS中执行此操作,则可以执行以下操作:

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

I think the spread operator is much cleaner and should go that route if you have access to it. 我认为点差操作员要干净得多,如果可以使用,应该走那条路线。

You can also achieve the same using the spread operator which allows you to have the new values in an object, instead of having to hardcode them: 您还可以使用散布运算符来实现相同目的,该运算符允许您在对象中拥有新值,而不必对它们进行硬编码:

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

const newSelectionValues = {
  timespan: "-3600",
  customTimespan: true
};

const newSelection = { ...selection, ...newSelectionValues };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM