我对 React 和 Redux 还很陌生。我正在开发一个 reducer ,并在尝试使用展开运算符时遇到编译错误。
export default function chaptersReducer(
state = { chapters: {}, isFetching: false, error: false },
action = {},
) {
switch (action.type) {
case REQUEST:
return { ...state, isFetching: true, error: false };
case SUCCESS:
return {
...state,
chapters: {
...state.chapters,
action.payload
},
isFetching: false
};
case FAILURE:
return { ...state, isFetching: false, error: true };
default:
return state;
}
}
我收到的具体错误是这样的。 (成功案例内)
Syntax error: Unexpected token, expected , (27:44)
> 27 | chapters: {...state.chapters, action.payload},
| ^
也许我遗漏了一些非常明显的东西,但是有人可以帮助我弄清楚发生了什么吗?
编辑:我正在使用create-react-app、redux和react-redux
最佳答案
chapters: {
...state.chapters,
action.payload
},
不太确定你要做什么,在这里
chapters: {
...state.chapters,
...action.payload
},
也许?
不指定键 ({ someProp }
) 是 { someProp: someProp }
的简写,并且需要简单的键(即 action.payload
不起作用)
无论哪种方式,您都需要一把 key ,即
chapters: {
...state.chapters,
chapterN: action.payload
},
或完全替换
chapters: action.payload
编辑:我看到你的评论
给定 action.payload
=> { someId: { ... 一些有效负载 ... } }
,
chapters: {
...state.chapters,
...action.payload
},
可能非常接近你想要的。如果您还将 mangaId
作为操作中的字段传递,即 { id: mangaId, Payload: { ... some Payload ... } }
,那么您会想要
chapters: {
...state.chapters,
[action.mangaId]: action.payload
},
关于javascript - 使用 React 和 Redux 传播运算符错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50195554/