出现Parsing error: Unexpected token, expected ','错误,无法定位缺失逗号位置
解决Parsing error: Unexpected token, expected ','错误
我遇到了Parsing error: Unexpected token, expected ','错误,无法定位缺失逗号的位置,相关代码如下:
const cartSlice = createSlice({ name: 'cartReducer', initialState, reducers: { CART_ADD_ITEM: (state, action) => { //checkout action.payload }, }, extraReducers: { [addToCart.pending]: (state) => { console.log(state); state.loading = true; }, [addToCart.fulfilled]: (state, action) => { console.log(state); const item = action.payload; const existItem = state.cartItems.find( (cartItem) => cartItem.product === item.product ); { existItem ? (state.cartItems = state.cartItems.map((cartItem) => { return { cartItem.product === existItem.product ? item : cartItem } })) : ((state.loading = false), (state.cartItems = [...state.cartItems, item])); } }, [addToCart.rejected]: (state, action) => { state.loading = true; state.error = action.payload; }, } });
错误原因定位
错误出现在[addToCart.fulfilled]回调里的map函数返回语句中:
return { cartItem.product === existItem.product ? item : cartItem }
这里的写法存在语法错误:你试图在对象字面量中直接放置一个三元表达式,但解析器无法识别这种结构——对象需要键值对,而非直接的条件表达式。另外,外层包裹条件判断的{ ... }也是多余的,会导致代码结构混乱。
修正后的代码
const cartSlice = createSlice({ name: 'cartReducer', initialState, reducers: { CART_ADD_ITEM: (state, action) => { //checkout action.payload }, }, extraReducers: { [addToCart.pending]: (state) => { console.log(state); state.loading = true; }, [addToCart.fulfilled]: (state, action) => { console.log(state); const item = action.payload; const existItem = state.cartItems.find( (cartItem) => cartItem.product === item.product ); if (existItem) { state.cartItems = state.cartItems.map(cartItem => cartItem.product === existItem.product ? item : cartItem ); } else { state.loading = false; state.cartItems = [...state.cartItems, item]; } }, [addToCart.rejected]: (state, action) => { state.loading = true; state.error = action.payload; }, } });
修正说明
- 移除了包裹条件判断的多余
{ ... },改用更清晰的if/else结构替代嵌套三元表达式,提升代码可读性。 - 修改
map函数的返回逻辑:直接返回三元表达式结果,不需要额外的对象字面量包裹——因为要返回的是完整的cartItem或item对象,而非新的键值对。 - 简化箭头函数写法:单行箭头函数省略冗余的大括号和
return关键字,让代码更简洁。
内容的提问来源于stack exchange,提问作者Usama BG
相关产品推荐
相关产品推荐

