使用扩展运算符更新对象的多个属性

时间:2022-08-30 10:00:29

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?

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

1 个解决方案

#1


6  

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:

如果你想用香草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.

我认为扩展操作符要干净得多,如果你有权限的话应该走那条路。

#1


6  

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:

如果你想用香草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.

我认为扩展操作符要干净得多,如果你有权限的话应该走那条路。