未处理的拒绝(类型错误):无法读取 react-redux 的未定义的属性"查找"



请帮我修复这个错误:Unhandled Rejection (TypeError): Cannot read property 'find' of undefined.

所有代码如下;

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
}

}

this is CartAction

import axios from 'axios'
import { CART_ADD_ITEM } from '../constants/cartConstants'

export const addToCart = (id, qty) => async (dispatch, getState) => {
const {data} = await axios.get(`/api/products/${id}`)
dispatch({
type: CART_ADD_ITEM,
payload: {
product: data._id,
name: data.name,
image: data.image,
price: data.price,
countInStock: data.countInStock,
qty
}
})
localStorage.setItem('cartItems', JSON.stringify(getState().cart.cartItems))

import { createStore, combineReducers, applyMiddleware } from 'redux'
import thunk from 'redux-thunk'
import { composeWithDevTools } from 'redux-devtools-extension'
import { listProducts, listProductDetails } from './reducers/productReducers'
import { cartReducer } from './reducers/cartReducers'

const cartFromLocalStorage = localStorage.getItem('cartITems') ? JSON.parse(localStorage.getItem('cartItems')) : []
**const initialState = {

cart: {cartITems:carfromlocalstorage}} * *

const reducer = combineReducers({
productsList: listProducts,
productDetails: listProductDetails,
cart: cartReducer,
})
const middleware = [thunk]
const store = createStore(
reducer,
initialState,
composeWithDevTools(applyMiddleware(...middleware))
)
export default store

如果发现同样的错误,而我给"cartFromLocalStorage"在initialState中,我在声明cart: { cartITems: cartFromLocalStorage }而不是cart: { cartItems: cartFromLocalStorage }时犯了错误,我在cartItems中使用了大写字母T,所以我纠正了它,现在添加到购物车工作正常,在这里输入图像描述

最新更新