未捕获的类型错误:无法读取购物车项目的未定义属性(读取“推送”)
2023-03-03
547
我正在创建购物车,可以将产品添加到购物车页面。但是当我单击添加到购物车按钮时,出现错误“Uncaught TypeError:无法读取未定义的属性(读取'push')”
这是我的代码
cartSlice.js
import { createSlice } from "@reduxjs/toolkit";
import { toast } from "react-toastify";
const initialState = {
cartItems: localStorage.getItem("cartItems") ? JSON.parse(localStorage.getItem("cartItems")) : [],
cartTotalQuantity: 0,
cartTotalAmount: 0,
};
const cartSlice = createSlice({
name: "cart",
initialState,
reducers: {
addToCart(state, action) {
let itemIndex = state.cartItems.findIndex(
(item) => item.id === action.payload.id
);
if (itemIndex >= 0) {
state.cartItems[itemIndex].cartQuantity += 1;
toast.info("added product to cart", { position: "top-center" });
} else {
const tempProduct = { ...action.payload, cartQuantity: 1 };
state.itemIndex.push(tempProduct);
toast.success("succes to add product", { position: "top-center" });
}
localStorage.setItem("cartItems", JSON.stringify(state.cartItems));
},
},
});
export const { addToCart } = cartSlice.actions;
export default cartSlice.reducer;
index.js
import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import { configureStore } from "@reduxjs/toolkit";
import { Provider } from "react-redux";
import { productsApi } from "./redux/productsAPI";
import productsReducer from "./redux/productSlice";
import cartReducer from "./redux/cartSlice";
const store = configureStore({
reducer: {
products: productsReducer,
cart: cartReducer,
[productsApi.reducerPath]: productsApi.reducer,
},
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().concat(productsApi.middleware),
});
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>
);
reportWebVitals();
Home.jsx
import React from "react";
import { useGetAllProductsQuery } from "../redux/productsAPI";
import { useNavigate } from "react-router";
import { useDispatch } from "react-redux";
import { addToCart } from "../redux/cartSlice";
const Home = () => {
const { data, error, isLoading } = useGetAllProductsQuery();
const navigate = useNavigate();
const dispatch = useDispatch();
const handleAddToCart = (product) => {
dispatch(addToCart(product));
navigate("/cart");
};
return (
<section className="px-4 py-12 w-full h-full flex flex-col items-center justify-center mt-10">
{isLoading ? (
<p className="duration-500">Loading...</p>
) : error ? (
<p>Oh no, there was an</p>
) : (
<>
<h2 className="font-bold text-2xl md:text-4xl mb-8">Products</h2>
<div className="grid grid-cols-2 lg:grid-cols-3 gap-6">
{data?.map((item) => (
<div
key={item.id}
className="flex flex-col items-center justify-center p-2 shadow-lg border border-gray-300"
>
<h3 className="mb-2 font-bold">{item.name}</h3>
<div className="w-full h-[250px] md:h-[350px]">
<img
className="w-full h-full object-contain"
src={item.image}
alt={item.name}
/>
</div>
<div className="w-full flex flex-col gap-3">
<div className="md:mt-4">
<p className="p-1 text-xs md:text-sm text-gray-600 font-bold">
{item.description}
</p>
<p className="p-1 font-bold">${item.price}</p>
</div>
<button
onClick={()=>handleAddToCart(item)}
className="w-full bg-red-600 text-white rounded-xl py-1 hover:bg-red-500"
>
Add to cart
</button>
</div>
</div>
))}
</div>
</>
)}
</section>
);
};
export default Home;
2个回答
由于 addToCart 化简器中的拼写错误。您尝试将对象推送到名为“state.itemIndex”的未定义变量中,但它应该是“state.cartItems”
reducers: {
addToCart(state, action) {
let itemIndex = state.cartItems.findIndex(
(item) => item.id === action.payload.id
);
if (itemIndex >= 0) {
state.cartItems[itemIndex].cartQuantity += 1;
toast.info("added product to cart", { position: "top-center" });
} else {
const tempProduct = { ...action.payload, cartQuantity: 1 };
state.cartItems.push(tempProduct);
toast.success("success to add product", { position: "top-center" });
}
localStorage.setItem("cartItems", JSON.stringify(state.cartItems));
},
},
Tsurule Vol
2023-03-03
cartSlice.js
else 语句中的
state.cartItems
而不是
state.itemIndex
。
Amaka
2023-03-03