本文介绍了使用扩展运算符更新对象的多个属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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: []
};

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

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?

推荐答案

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

You need to remove the extra object closure from there

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

应该没问题

如果你想在 vanilla JS 中做到这一点,你可以这样做:

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.

这篇关于使用扩展运算符更新对象的多个属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-15 12:15