我正在学习MERN STACK教程,在设置我的购物车时这就是我得到的错误,但是,我安慰道。将数据记录在我的reducer中,它正在显示,但不知道为什么它会显示这个错误
Unhandled Rejection (TypeError): state.cartItems is undefined
此外,为什么导师使用localStorage存储数据,我们不能在获取Cart Action后直接将其发送到reducer。。。它与有何关联
谢谢
纸箱操作
import { ADD_TO_CART } from '../constants/CartConstants';
import axios from "axios";
export const addToCart = (id, qty) => async (dispatch, getState) => {
const { data } = await axios.get(`/api/products/${id}`);
dispatch({
type: ADD_TO_CART,
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 , applyMiddleware, combineReducers} from 'redux';
import thunk from 'redux-thunk'
import {composeWithDevTools} from 'redux-devtools-extension';
import {productListReducer , productDetailsReducer } from './reducers/productReducer' ;
import {cartReducer} from "./reducers/cartReducer"
const reducer = combineReducers({
productList: productListReducer,
productDetails:productDetailsReducer,
cart: cartReducer
});
const cartItemsFromStorage = localStorage.getItem('cartItems') ? JSON.parse(localStorage.getItem('cartItems')) : []
const initialState = {
cart: cartItemsFromStorage
};
const middleware = [thunk];
const store = createStore(reducer , initialState , composeWithDevTools(applyMiddleware(...middleware)))
//composite with dev tools is used to connect our store with our devtools
export default store;
纸箱减速器
import { ADD_TO_CART } from '../constants/CartConstants';
export const cartReducer = (state = { cartItems: [] }, action) => {
switch (action.type) {
case ADD_TO_CART:
const item = action.payload;
const existItem = state.cartItems.find((x) => x.product === item.product)
console.log(existItem)
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
}
}
我知道这是一个老问题,但如果有人面临同样的问题,答案是
取代这个:
const initialState = {cart: cartItemsFromStorage};
这个:
const initialState = { cart: { cartItems: cartItemsFromStorage } };
在商店.js
确保这与您的状态结构匹配
localStorage.setItem('cartItems', JSON.stringify(getState().*cart.cartItems*))
如果你的名字不同,它可能会改变,例如
cartReducer.cartItems