简体   繁体   English

未处理的拒绝(TypeError):state.cartItems 未定义

[英]Unhandled Rejection (TypeError): state.cartItems is undefined

I was a following a MERN STACK tutorial and while setting my cart This is the error I am getting but, I console.log the data in my reducer and it's showing but don't know why is it showing this error我正在关注 MERN STACK 教程,在设置我的购物车时这是我得到的错误,但是,我 console.log 在我的减速器中记录数据,它正在显示,但不知道为什么会显示这个错误

Unhandled Rejection (TypeError): state.cartItems is undefined

Also, why is the tutor using localStorage for storing data, Can't we directly send it to reducer after fetching Cart Action... How is it related还有,为什么导师用localStorage来存储数据,难道我们不能在获取Cart Action之后直接发送给reducer吗……这有什么关系

Thank You谢谢你

CART ACTION购物车行动

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))

STORE店铺

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;

CART REDUCER推车减速器

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
    }
}

Make sure this matches your state structure确保这与您的 state 结构匹配

localStorage.setItem('cartItems', JSON.stringify(getState().*cart.cartItems*))

If you named differently, it may change eg如果你命名不同,它可能会改变,例如

cartReducer.cartItems

i know it is an old question,but in case someone is facing the same problem, the answer is我知道这是一个老问题,但如果有人面临同样的问题,答案是

to replace this:替换这个:

const initialState = {cart: cartItemsFromStorage};

with this:有了这个:

const initialState = { cart: { cartItems: cartItemsFromStorage } };

in the store.js在 store.js 中

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 未处理的拒绝(TypeError):state.recipes 未定义 - Unhandled Rejection (TypeError): state.recipes is undefined 未处理的拒绝(TypeError):无法读取未定义的属性(读取“状态”) - Unhandled Rejection (TypeError): Cannot read properties of undefined (reading 'state') 反应未处理的拒绝(TypeError):无法读取未定义的属性“状态” - React Unhandled Rejection (TypeError): Cannot read property 'state' of undefined 未处理的拒绝(TypeError):无法读取未定义的属性 - Unhandled Rejection (TypeError): Cannot read property of undefined 将图像上传到 Firebase 存储:未处理的拒绝(类型错误):无法读取未定义的属性“状态” - Uploading image to firebase storage: Unhandled Rejection (TypeError): Cannot read property 'state' of undefined 未处理的拒绝 (TypeError):error.response 未定义 - Unhandled Rejection (TypeError): error.response is undefined [未处理的 promise 拒绝:TypeError: undefined is not an object(评估'this.state.result.map')] - [Unhandled promise rejection: TypeError: undefined is not an object (evaluating 'this.state.result.map')] 无法使用 gatsby 设置 state 反应未处理的拒绝(TypeError):无法读取未定义的属性“setState” - cannot set state with gatsby react Unhandled Rejection (TypeError): Cannot read property 'setState' of undefined 反应 - Redux | 未处理的拒绝(类型错误):无法读取未定义的属性“数据” - React - Redux | Unhandled Rejection (TypeError): Cannot read property 'data' of undefined 未处理的拒绝(TypeError):无法读取未定义的属性“ id” - Unhandled Rejection (TypeError): Cannot read property 'id' of undefined
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM