You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

购物车页面图片渲染成功后变为undefined的问题求助

购物车页面图片渲染成功后变为undefined的问题求助

我遇到了一个非常费解的问题:明明已经从数据库成功获取到图片URL并完成渲染,可过一会儿图片就突然变成了undefined。在其他页面我用完全相同的方式处理图片都没有问题,唯独购物车页面出现这个情况,完全摸不着解决的头绪。

问题相关代码

购物车页面(Cart.js)

"use client";
import React, { useState, useEffect } from "react";
import { useSelector, useDispatch } from "react-redux";
import { fetchCartItems } from "@/redux/cart/cartSlice";
import CartItem from "@/components/CartItem";
import { Button } from "antd";
const Cart = () => {
  const { currentUser } = useSelector((state) => state.auth);
  const { cartItems } = useSelector((state) => state.cart);
  const [error, setError] = useState(null);
  const [loading, setLoading] = useState(false);
  const dispatch = useDispatch();
  const userId = currentUser._id;

  const totalPrice = cartItems.reduce(
    (summedPrice, product) =>
      summedPrice +
      (product.promotionRate || product.promotionRate > 0
        ? product.price - product.price * (product.promotionRate / 100)
        : product.price) *
        product.quantity,
    0
  );

  useEffect(() => {
    setLoading(true);
    const fetchProducts = async () => {
      try {
        const res = await fetch(
          `http://localhost:8000/backend/cart/getCartItems/:${userId}`
        );
        const data = await res.json();
        if (data.success === false) {
          setLoading(false);
          setError(data.message);
        }
        dispatch(fetchCartItems(data.data.items));
      } catch (error) {
        setError(error.message);
        setLoading(false);
      }
    };
    fetchProducts();
  }, []);

  return (
    <div className="flex w-full m-auto justify-between bg-gray-300">
      <div className="border w-1/6 bg-white m-2 rounded-md flex flex-col items-center pt-2 h-[250px] min-h-[200px]">
        <div className="flex justify-between w-full px-10">
          <p>{cartItems.length}</p>
          <p>عدد السلع</p>
        </div>
        <div className="flex justify-between w-full px-10 mt-10">
          <p>{totalPrice}</p>
          <p>اجمالي السعر</p>
        </div>
        <div className="pt-4 flex item">
          <button className="bg-accent text-center text-white px-4 py-2 mt-4 rounded-md hover:bg-primary">
            استمر في الشراء
          </button>
        </div>
      </div>
      {!currentUser ? (
        <div>
          <p>Pleas sign in</p>
        </div>
      ) : (
        <div className="flex-1  w-10/12 bg-white m-2 rounded-md">
          {cartItems.map((item) => (
            <CartItem userId={currentUser._id} product={item} />
          ))}
        </div>
      )}
    </div>
  );
};

export default Cart;

购物车项组件(CartItem.js)

"use client";
import { fetchCartItems } from "@/redux/cart/cartSlice";
import Image from "next/image";
import React, { useEffect, useState } from "react";
import { useDispatch } from "react-redux";
const cartItem = ({ userId, product }) => {
  const [itemQuantity, setItemQuantity] = useState(product.quantity);
  const [error, setError] = useState(null);
  const [loading, setLoading] = useState(false);
  const dispatch = useDispatch();

  useEffect(() => {
    setLoading(true);
    const updateCartProduct = async () => {
      try {
        const res = await fetch(
          "http://localhost:8000/backend/cart/updateCart",
          {
            method: "PUT",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({
              userId,
              productId: product.productId,
              quantity: itemQuantity,
            }),
          }
        );

        const data = await res.json();

        if (data.success === false) {
          setLoading(false);
          setError(data.message);
        }
        dispatch(fetchCartItems(data.data.items));
      } catch (error) {
        setError(error.message);
        setLoading(false);
      }
    };
    updateCartProduct();
  }, [itemQuantity]);

  console.log(product.image);
  return (
    <div className="w-full">
      <div className="w-1/2 border-t-2 m-auto mt-6 pt-4 pb-8 flex justify-between ">
        {/* price on the left side  */}
        <div className="gap-1 flex">
          <p>جنيه</p>
          <p className="pt-1">{product.price}</p>
        </div>
        {/* title on the middle */}

        <div className="flex flex-col">
          <div>
            <p>{product.title}</p>
          </div>
          <div className="flex gap-10 justify-center mt-10">
            <div className="">
              <i
                onClick={() => setItemQuantity(Math.max(1, itemQuantity - 1))}
                class="cursor-pointer ri-subtract-line"
              ></i>{" "}
            </div>
            <p>{itemQuantity}</p>
            <div>
              <i
                onClick={() => setItemQuantity(itemQuantity + 1)}
                class="cursor-pointer ri-add-line"
              ></i>
            </div>
            <p>الكمية</p>
          </div>
        </div>

        {/* image on the right  */}

        <div>
          {!product.image ? (
            ""
          ) : (
            <Image
              src={product.image}
              width={100}
              height={100}
              alt={product.title}
            />
          )}
        </div>
      </div>
    </div>
  );
};

export default cartItem;

后端控制器代码

export const fetchCartItems = async (req, res) => {
  try {
    const { userId } = req.params;

    const id = userId.slice(1);

    if (!id) {
      return res.status(400).json({
        success: false,
        message: "User id is manadatory!",
      });
    }

    const cart = await Cart.findOne({ userId: id }).populate({
      path: "items.productId",
      select: "images title price promotionRate",
    });

    if (!cart) {
      return res.status(404).json({
        success: false,
        message: "Cart not found!",
      });
    }

    const validItems = cart.items.filter(
      (productItem) => productItem.productId
    );

    if (validItems.length < cart.items.length) {
      cart.items = validItems;
      await cart.save();
    }

    const populateCartItems = validItems.map((item) => ({
      productId: item.productId._id,
      image: item.productId.images[0],
      title: item.productId.title,
      price: item.productId.price,
      promotionRate: item.productId.promotionRate,
      quantity: item.quantity,
    }));
    res.status(200).json({
      success: true,
      data: {
        ...cart._doc,
        items: populateCartItems,
      },
    });
  } catch (error) {
    console.log(error);
    res.status(500).json({
      success: false,
      message: "Error",
    });
  }
};

控制台日志情况

我在CartItem组件里打印了product.image,控制台先是输出正确的图片URL,紧接着就变成了undefined:
控制台日志截图

Redux reducer的日志也显示了同样的异常:
Reducer控制台日志截图

其他页面用相同的逻辑处理图片完全正常,唯独购物车页面出现这个问题,有没有人能帮我分析一下问题出在哪里?

备注:内容来源于stack exchange,提问作者Mohammed Refat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 14:59:34