阵列内的多个嵌套排列运算符(javascript es2015)
我正在使用React/Redux体系结构处理一个减速机。这与我的问题无关,因为这更像是一个ES2015问题。我有以下代码:阵列内的多个嵌套排列运算符(javascript es2015),javascript,ecmascript-6,Javascript,Ecmascript 6,我正在使用React/Redux体系结构处理一个减速机。这与我的问题无关,因为这更像是一个ES2015问题。我有以下代码: return objectAssign({}, state, { sendingRequest: false, currentModel: { ...state.currentModel, components: [ ...state.currentModel.c
return objectAssign({}, state, {
sendingRequest: false,
currentModel: {
...state.currentModel,
components: [
...state.currentModel.components,
0: {
...state.currentModel.components[0], // can't do this, why?
selectedComponentGroup: {
...state.currentModel.components[0].selectedComponentGroup,
availableComponents: action.payload.data
}
}
]
}
});
但是,ESLint抛出了一个错误:
✘ http://eslint.org/docs/rules/ Parsing error: Unexpected token
C:\...\ProjectModelsReducer.js:122:25
...state.currentModel.components[action.componentIndex],
它特别抱怨这条线路的扩展运营商:
...state.currentModel.components[action.componentIndex]
我不明白为什么这不起作用,我想知道是否有人能解释为什么这里不能使用扩展运算符。我现在明白我的错误了。我将数组视为一个对象,并使用索引作为数组中的键,但数组在定义键时不使用键。我必须这样做:
components: [
...state.currentModel.components,
{
0: {
...state.currentModel.components[0],
selectedComponentGroup: {
...state.currentModel.components[0].selectedComponentGroup,
availableComponents: action.payload.data
}
}
}
]
最终,我使用了,使更新更干净
components: update(state.currentModel.components, {
0: {
$merge: {
selectedComponentGroup: {
...state.currentModel.components[0].selectedComponentGroup,
availableComponents: action.payload.data
}
}
}
})
无效,就像[0:{}]
作为数组声明无效一样。如果要创建一个新的数组并更改特定项,则必须使用spread和普通数组语法,或者克隆数组并在以后修改索引,例如
components: [
{
// ...
},
...state.currentModel.components.slice(1),
]
要在替换第一项的情况下创建新数组,请执行以下操作:
components: Object.assign([...state.currentModel.components], {
0: {
// ...
}
}),
要克隆数组,请更改
0
索引处的项。听起来您已经为Babel启用了实验性stage-x
功能,但没有将ESLint配置为使用Babel进行解析。扩展对象不是标准的ECMAScript。数组文本中不能有0:
。哦,很好的调用,忽略了扩展是一个数组而不是对象,所以这通常是一个语法错误,而不仅仅是ESLint。@Bergi为什么?如何更改数组索引为0的对象的内容?是的,这就是我出错的地方。Redux减缩器的声明性本质让我搞砸了。看代码的漫长一天。需要一些额外的眼睛:)。你的第二个例子基本上就是我所缺少的。谢谢有什么地方可以让我学到这些吗?(将操作符对象扩展到基础之外,并附有示例)我看到的每个教程都显示了相同的内容
components: Object.assign([...state.currentModel.components], {
0: {
// ...
}
}),