Update Multiple Properties of an object with spread operator

*爱你&永不变心* 提交于 2019-12-22 08:25:51

问题


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):

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

How can I update multiple properties of a state?


回答1:


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:

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.




回答2:


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 };


来源:https://stackoverflow.com/questions/41878169/update-multiple-properties-of-an-object-with-spread-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!