我正在尝试从本地存储设置购物车数据,并将其设置在购物车项目上。我已经在本地存储中设置了购物车数据。但当我试图将本地存储的数据设置到购物车中时,我遇到了一些问题。当我试图设置它时,我无法在那里正确设置它。也许这就是我面临的问题。这是推车减速器代码
import { useState } from "react";
import { SHOW_HIDE_CART, ADD_TO_CART, REMOVE_ITEM } from "../Types";
const CartReducer = (state, action) => {
const cartDataFromLocal = JSON.parse(localStorage.getItem('cartItem');
switch (action.type) {
case SHOW_HIDE_CART: {
return {
...state,
showCart: !state.showCart,
};
}
case ADD_TO_CART: {
return {
...state,
cartItems: [...state.cartItems, action.payload],
};
}
case REMOVE_ITEM: {
return {
...state,
cartItems: state.cartItems.filter(
(item) => item._id !== action.payload
),
};
}
default:
return state;
}
};
export default CartReducer;
这是购物车状态的代码
import { useState } from "react";
import { SHOW_HIDE_CART, ADD_TO_CART, REMOVE_ITEM } from "../Types";
const CartReducer = (state, action) => {
const cartDataFromLocal = JSON.parse(localStorage.getItem('cartItem'))
switch (action.type) {
case SHOW_HIDE_CART: {
return {
...state,
showCart: !state.showCart,
};
}
case ADD_TO_CART: {
return {
...state,
cartItems: [...state.cartItems, action.payload],
};
}
case REMOVE_ITEM: {
return {
...state,
cartItems: state.cartItems.filter(
(item) => item._id !== action.payload
),
};
}
default:
return state;
}
};
export default CartReducer;
我没有看到你在任何地方使用cartDataFromLocal
变量,你需要用你的有效负载中的本地存储的内容来调度之前的操作:
// in component
dispatch(addItemToCart(cartDataFromLocal));
// in actions
const addItemToCart = (cartDataFromLocal) => (dispatch) => {
dispatch({
type: 'ADD_TO_CART',
payload: cartDataFromLocal
})
}