使用扩展运算符更新对象的多个属性
Update Multiple Properties of an object with spread operator
我在减速器中有一个如下所示的状态:
// 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
}
};
如何更新状态的多个属性?
你需要从那里删除额外的对象闭包
{ ...state,
timespan: action.timespan.value,
customTimespan: action.timespan.value
}
应该没问题
如果你想用 vanilla JS 来做,你可以这样做:
Object.assign({}, state, { timespan: action.timespan.value, customTimespan: action.timespan.value})
我认为传播运算符更简洁,如果您可以访问它,应该走这条路。
您也可以使用扩展运算符实现相同的目的,它允许您在对象中拥有新值,而不必对它们进行硬编码:
const selection = {
timespan: "-3660",
customTimespan: false,
pathIds: [""],
source: undefined,
direction: 0,
appClassIds: []
};
const newSelectionValues = {
timespan: "-3600",
customTimespan: true
};
const newSelection = { ...selection, ...newSelectionValues };
我在减速器中有一个如下所示的状态:
// 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
}
};
如何更新状态的多个属性?
你需要从那里删除额外的对象闭包
{ ...state,
timespan: action.timespan.value,
customTimespan: action.timespan.value
}
应该没问题
如果你想用 vanilla JS 来做,你可以这样做:
Object.assign({}, state, { timespan: action.timespan.value, customTimespan: action.timespan.value})
我认为传播运算符更简洁,如果您可以访问它,应该走这条路。
您也可以使用扩展运算符实现相同的目的,它允许您在对象中拥有新值,而不必对它们进行硬编码:
const selection = {
timespan: "-3660",
customTimespan: false,
pathIds: [""],
source: undefined,
direction: 0,
appClassIds: []
};
const newSelectionValues = {
timespan: "-3600",
customTimespan: true
};
const newSelection = { ...selection, ...newSelectionValues };