首页 > 解决方案 > 添加到 redux-toolkit 中的购物车(状态未定义),有人请帮帮我吗?

问题描述

我正在尝试将产品添加到购物车。

我不明白为什么状态未定义,

我有一个 localStorage '购物车':

(3) [{…}, {…}, {…}]

0: {product: {…}, quantity: 1}

1: {product: {…}, quantity: 2}

console.log(action.payload): 
  {product: {…}, quantity: 1}

当我单击添加购物车按钮时,我的 localStorage 添加正确,但状态自动丢失

我的代码 cartSlice.js:

import { createSlice } from '@reduxjs/toolkit';
import {
  createCart,
  getCart,
  updateCart,
  deleteCart
} from './../asyncActions/cart.asyncAction';
var data = JSON.parse(localStorage.getItem('cart'));
const cartSlice = createSlice({
  name: 'cart',
  initialState: {
    cart: data ? data : [],
    searchValue: '',
  },
  reducers: {
  },
  extraReducers: {
    //* get cart
    [getCart.pending]: (state, action) => {
    },
    [getCart.fulfilled]: (state, action) => {
      if (action.payload) {
        state.cart = action.payload;
      }
    },
    [getCart.rejected]: (state, action) => {
    },

    // create
    [createCart.pending]: (state, action) => {
    },
    [createCart.fulfilled]: (state, action) => {
      if (action.payload) {
        let idProductAction = action.payload.product.id;
        var index = state.cart ? state.cart.map((item) => item.product.id).indexOf(idProductAction) : -1;
        if(index !== -1){
            state.cart[index].quantity += action.payload.quantity;
        } else {
            state.cart = [action.payload, ...state.cart];
        }
        state.cart = localStorage.setItem('cart', JSON.stringify(state.cart));
      }
    },
    [createCart.rejected]: (state, action) => {
        console.log('sai');
    },

  }
});

const { actions, reducer } = cartSlice;

const { clearStateCart } = actions;

export { clearStateCart };

export default reducer;

我的代码组件 Cart.js:

import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { getCart, createCart } from '../../store/asyncActions/cart.asyncAction';

function Cart(props) {
    const classes = useStyles();
    const dispatch = useDispatch();
    let cart = useSelector((state) => state.cart.cart);
    let productList = useSelector((state) => state.products.products);

    const addCart = (product) => {
      getDispatchCreateCart(product);
    }

    const getDispatchCreateCart = (product) => {
      dispatch (
          createCart({
              product: product,
              quantity: 1
          })
      )
    }

    const getDispatchProducts = () => {
      dispatch (
          getProducts()
      )
    }
    const getDispatchGetCart = () => {
      dispatch (
          getCart()
      )
    }

    useEffect(() => {
      getDispatchProducts();
      getDispatchGetCart();
    }, []);

    return (...);
}
export default Cart;

我的 redux devtools 显示:

我不明白为什么状态未定义,希望大家帮忙。

标签: reactjsreduxreact-reduxredux-toolkit

解决方案


你不能 state.cart,它会被 localStorage typeof undefined 丢失:

state.cart = localStorage.setItem('cart', JSON.stringify(state.cart));

编辑:

[createCart.fulfilled]: (state, action) => {
      if (action.payload) {
        let idProductAction = action.payload.product.id;
        var index = state.cart ? state.cart.map((item) => item.product.id).indexOf(idProductAction) : -1;
        if(index !== -1){
            state.cart[index].quantity += action.payload.quantity;
        } else {
            state.cart = [action.payload, ...state.cart];
        }
        localStorage.setItem('cart', JSON.stringify(state.cart));
      }
    },

推荐阅读