...
import {
CART_ADD_ITEM,
} from '../constants/cartConstants'
export const cartReducer = (
state = { cartItems: []},
action
) => {
switch (action.type) {
case CART_ADD_ITEM:
const item = action.payload
const existItem = state.cartItems.find((x) => x.product === item.product)
if (existItem) {
return {
...state,
cartItems: state.cartItems.map((x) =>
x.product === existItem.product ? item : x
),
}
} else {
return {
...state,
cartItems: [...state.cartItems, item],
}
}
default:
return state
}
}
误差
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'find')
at cartReducer
1条答案
按热度按时间rkttyhzu1#
该错误表示无法在未定义的对象上调用“find”方法。很可能是传递给Reducer的状态对象未定义,导致“state.cartItems”也未定义。要解决此问题,请确保在Reducer中正确定义初始状态对象,例如state = {cartItems:[]}.