英文:
Uncaught TypeError: Cannot read properties of undefined (reading 'push') for shopping cart project
问题
我创建了一个可以将产品添加到购物车页面的购物车。但是当我点击"添加到购物车"按钮时,出现了一个错误:"Uncaught TypeError: Cannot read properties of undefined (reading '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("已添加产品到购物车", { position: "top-center" });
} else {
const tempProduct = { ...action.payload, cartQuantity: 1 };
state.cartItems.push(tempProduct); // 修复此处错误,应该是state.cartItems.push而不是state.itemIndex.push
toast.success("成功添加产品", { 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";
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">加载中...</p>
) : error ? (
<p>哦,出现了一个错误</p>
) : (
<>
<h2 className="font-bold text-2xl md:text-4xl mb-8">产品</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"
>
添加到购物车
</button>
</div>
</div>
))}
</div>
</>
)}
</section>
);
};
export default Home;
请注意,在cartSlice.js
中的错误已经修复。修复后,应该可以正常添加产品到购物车。如果还有其他问题,请随时提出。
英文:
I'm creating shooping cart that can add product to cart page. But when I click the add to cart button, there is an error "Uncaught TypeError: Cannot read properties of undefined (reading 'push')"
thees is my code
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;
I've search the problem solving but I can't get through this problem. Thankyou for your help guys
答案1
得分: 1
因为在addToCart reducer中有一个拼写错误。您试图将一个对象推送到一个未定义的变量名为“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));
},
},
英文:
because of a typo in the addToCart reducer. You are trying to push an object into an undefined variable named "state.itemIndex", but it should be "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));
},
},
答案2
得分: 0
cartSlice.js
中的 else 语句中应该使用 state.cartItems
而不是 state.itemIndex
。
英文:
state.cartItems
not state.itemIndex
in cartSlice.js
else statement.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论