redux 未捕获(承诺中)TypeError:无法读取cartReducer处未定义(读取"find")的属性

wwodge7n  于 2023-01-30  发布在  其他
关注(0)|答案(1)|浏览(128)
...
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
rkttyhzu

rkttyhzu1#

该错误表示无法在未定义的对象上调用“find”方法。很可能是传递给Reducer的状态对象未定义,导致“state.cartItems”也未定义。要解决此问题,请确保在Reducer中正确定义初始状态对象,例如state = {cartItems:[]}.

相关问题