Uncaught TypeError: 无法读取未定义的属性(读取 ‘push’),适用于购物车项目

huangapple go评论71阅读模式
英文:

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 &quot;@reduxjs/toolkit&quot;;
import { toast } from &quot;react-toastify&quot;;
const initialState = {
cartItems: localStorage.getItem(&quot;cartItems&quot;) ? JSON.parse(localStorage.getItem(&quot;cartItems&quot;)) : [],
cartTotalQuantity: 0,
cartTotalAmount: 0,
};
const cartSlice = createSlice({
name: &quot;cart&quot;,
initialState,
reducers: {
addToCart(state, action) {
let itemIndex = state.cartItems.findIndex(
(item) =&gt; item.id === action.payload.id
);
if (itemIndex &gt;= 0) {
state.cartItems[itemIndex].cartQuantity += 1;
toast.info(&quot;added product to cart&quot;, { position: &quot;top-center&quot; });
} else {
const tempProduct = { ...action.payload, cartQuantity: 1 };
state.itemIndex.push(tempProduct);
toast.success(&quot;succes to add product&quot;, { position: &quot;top-center&quot; });
}
localStorage.setItem(&quot;cartItems&quot;, JSON.stringify(state.cartItems));
},
},
});
export const { addToCart } = cartSlice.actions;
export default cartSlice.reducer;

index.js

import React from &quot;react&quot;;
import ReactDOM from &quot;react-dom/client&quot;;
import &quot;./index.css&quot;;
import App from &quot;./App&quot;;
import reportWebVitals from &quot;./reportWebVitals&quot;;
import { configureStore } from &quot;@reduxjs/toolkit&quot;;
import { Provider } from &quot;react-redux&quot;;
import { productsApi } from &quot;./redux/productsAPI&quot;;
import productsReducer from &quot;./redux/productSlice&quot;;
import cartReducer from &quot;./redux/cartSlice&quot;;
const store = configureStore({
reducer: {
products: productsReducer,
cart: cartReducer,
[productsApi.reducerPath]: productsApi.reducer,
},
middleware: (getDefaultMiddleware) =&gt;
getDefaultMiddleware().concat(productsApi.middleware),
});
const root = ReactDOM.createRoot(document.getElementById(&quot;root&quot;));
root.render(
&lt;React.StrictMode&gt;
&lt;Provider store={store}&gt;
&lt;App /&gt;
&lt;/Provider&gt;
&lt;/React.StrictMode&gt;
);
reportWebVitals();

Home.jsx

import React from &quot;react&quot;;
import { useGetAllProductsQuery } from &quot;../redux/productsAPI&quot;;
import { useNavigate } from &quot;react-router&quot;;
import { useDispatch } from &quot;react-redux&quot;;
import { addToCart } from &quot;../redux/cartSlice&quot;;
const Home = () =&gt; {
const { data, error, isLoading } = useGetAllProductsQuery();
const navigate = useNavigate();
const dispatch = useDispatch();
const handleAddToCart = (product) =&gt; {
dispatch(addToCart(product));
navigate(&quot;/cart&quot;);
};
return (
&lt;section className=&quot;px-4 py-12 w-full h-full flex flex-col items-center justify-center mt-10&quot;&gt;
{isLoading ? (
&lt;p className=&quot;duration-500&quot;&gt;Loading...&lt;/p&gt;
) : error ? (
&lt;p&gt;Oh no, there was an&lt;/p&gt;
) : (
&lt;&gt;
&lt;h2 className=&quot;font-bold text-2xl md:text-4xl mb-8&quot;&gt;Products&lt;/h2&gt;
&lt;div className=&quot;grid grid-cols-2 lg:grid-cols-3 gap-6&quot;&gt;
{data?.map((item) =&gt; (
&lt;div
key={item.id}
className=&quot;flex flex-col items-center justify-center p-2 shadow-lg border border-gray-300&quot;
&gt;
&lt;h3 className=&quot;mb-2 font-bold&quot;&gt;{item.name}&lt;/h3&gt;
&lt;div className=&quot;w-full h-[250px] md:h-[350px]&quot;&gt;
&lt;img
className=&quot;w-full h-full object-contain&quot;
src={item.image}
alt={item.name}
/&gt;
&lt;/div&gt;
&lt;div className=&quot;w-full flex flex-col gap-3&quot;&gt;
&lt;div className=&quot;md:mt-4&quot;&gt;
&lt;p className=&quot;p-1 text-xs md:text-sm text-gray-600 font-bold&quot;&gt;
{item.description}
&lt;/p&gt;
&lt;p className=&quot;p-1 font-bold&quot;&gt;${item.price}&lt;/p&gt;
&lt;/div&gt;
&lt;button
onClick={()=&gt;handleAddToCart(item)}
className=&quot;w-full bg-red-600 text-white rounded-xl py-1 hover:bg-red-500&quot;
&gt;
Add to cart
&lt;/button&gt;
&lt;/div&gt;
&lt;/div&gt;
))}
&lt;/div&gt;
&lt;/&gt;
)}
&lt;/section&gt;
);
};
export default Home;

I've search the problem solving but I can't get through this problem. Thankyou for your help guys Uncaught TypeError: 无法读取未定义的属性(读取 ‘push’),适用于购物车项目 Uncaught TypeError: 无法读取未定义的属性(读取 ‘push’),适用于购物车项目

答案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) =&gt; item.id === action.payload.id
);
if (itemIndex &gt;= 0) {
state.cartItems[itemIndex].cartQuantity += 1;
toast.info(&quot;added product to cart&quot;, { position: &quot;top-center&quot; });
} else {
const tempProduct = { ...action.payload, cartQuantity: 1 };
state.cartItems.push(tempProduct);
toast.success(&quot;success to add product&quot;, { position: &quot;top-center&quot; });
}
localStorage.setItem(&quot;cartItems&quot;, JSON.stringify(state.cartItems));
},
},

答案2

得分: 0

cartSlice.js 中的 else 语句中应该使用 state.cartItems 而不是 state.itemIndex

英文:

state.cartItems not state.itemIndex in cartSlice.js else statement.

huangapple
  • 本文由 发表于 2023年3月3日 22:34:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/75628377.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定