[英]Change property in array with Spread Operator returns object instead of array
我想更改类似于此的对象的属性,这是一个简化的对象,具有原始的一些属性:
state = {
pivotComuns: [
{
id: 1,
enabled : true
},
{
id: 2,
enabled : true
}
],
otherProperties : "otherProperties"
}
我正在改变启用状态,如下所示:
state = {
...state,
pivotColumns: {
...state.pivotColumns,
[2]: {
...state.pivotColumns[2], enabled: !state.pivotColumns[2].enabled
}
}
}
它可以工作,但是返回一个像我这样的数组是pivotComuns属性,它返回一个对象,“注意我为{}更改了[]”:
state = {
pivotComuns: {
{
id: 1
enabled : true
},
{
id: 2,
enabled : true
}
},
otherProperties : "otherProperties"
}
我做错了什么,我需要保持该属性为数组。
帖子很晚,但为了将来参考,您可以执行以下操作:
state = {
...state,
pivotColumns: state.pivotColumns.map(pc =>
pc.id === 2 ? {...pc, enabled:!pc.enabled} : pc
)
}
优点是您不会更改“旧数组”中引用的对象,而是在其位置插入新对象。 因此,如果你想在州内来回走动,你现在可以这样做。
我不相信你可以以这种方式使用扩展运算符,事实上如果你可以不推荐它,因为它会创建非常难以阅读的代码。 在更新值为数组的对象上的键/值时,我每天都会使用一个更简单的解决方案:
var state = {
pivotColumns: [
{
id: 1,
enabled : true
}, {
id: 2,
enabled : true
}
],
otherProperties : "otherProperties"
}
var clonedPivotColumns = state.pivotColumns.slice();
clonedPivotColumns[1].enabled = !state.pivotColumns[1].enabled;
state = {
...state,
pivotColumns: clonedPivotColumns
}
这将为您提供正确的结果,不会导致任何突变。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.