Anonymous
Изображение превращается в неопределенное после успешного рендеринга
Сообщение
Anonymous » 24 янв 2025, 13:14
Изображение превращается в неопределенное после успешного рендеринга. Я успешно решаю изображения из базы данных, и они превращаются в Undefine. Я не знаю, почему это происходит. < /P>
Это страница тележки < /p>
Код: Выделить всё
"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 (
{cartItems.length}
عدد السلع
{totalPrice}
اجمالي السعر
استمر في الشراء
{!currentUser ? (
Pleas sign in
) : (
{cartItems.map((item) => (
))}
)}
);
};
export default Cart;
а это компонент корзины
Код: Выделить всё
"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 (
{/* price on the left side */}
جنيه
{product.price}
{/* title on the middle */}
{product.title}
[i] onClick={() => setItemQuantity(Math.max(1, itemQuantity - 1))}
class="cursor-pointer ri-subtract-line"
>[/i]{" "}
{itemQuantity}
[i] onClick={() => setItemQuantity(itemQuantity + 1)}
class="cursor-pointer ri-add-line"
>[/i]
الكمية
{/* image on the right */}
{!product.image ? (
""
) : (
)}
);
};
export default cartItem;
это журнал консоли
Я понятия не имею, как это решить. Я делаю то же самое на других страницах, но при получении изображений не получаю неопределенности.
Подробнее здесь:
https://stackoverflow.com/questions/793 ... ccessfully
1737713659
Anonymous
Изображение превращается в неопределенное после успешного рендеринга. Я успешно решаю изображения из базы данных, и они превращаются в Undefine. Я не знаю, почему это происходит. < /P> Это страница тележки < /p> [code]"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 ( {cartItems.length} عدد السلع {totalPrice} اجمالي السعر استمر في الشراء {!currentUser ? ( Pleas sign in ) : ( {cartItems.map((item) => ( ))} )} ); }; export default Cart; [/code] а это компонент корзины [code]"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 ( {/* price on the left side */} جنيه {product.price} {/* title on the middle */} {product.title} [i] onClick={() => setItemQuantity(Math.max(1, itemQuantity - 1))} class="cursor-pointer ri-subtract-line" >[/i]{" "} {itemQuantity} [i] onClick={() => setItemQuantity(itemQuantity + 1)} class="cursor-pointer ri-add-line" >[/i] الكمية {/* image on the right */} {!product.image ? ( "" ) : ( )} ); }; export default cartItem; [/code] это журнал консоли [img]https://i.sstatic.net/3Kgkjc4l .png[/img] Я понятия не имею, как это решить. Я делаю то же самое на других страницах, но при получении изображений не получаю неопределенности. Подробнее здесь: [url]https://stackoverflow.com/questions/79383956/image-turns-to-undefined-after-rendering-successfully[/url]