"use client"; import { useEffect, useState, Suspense } from "react"; import { useRouter, useSearchParams } from "next/navigation"; import Image from "next/image"; import PaymentModal from "@/components/PaymentModal"; function CheckoutContent() { const router = useRouter(); const searchParams = useSearchParams(); const [products, setProducts] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [address, setAddress] = useState(null); const [showPaymentModal, setShowPaymentModal] = useState(false); // 获取地址的函数 const fetchAddress = async (token) => { const addressRes = await fetch("/api/address", { headers: { Authorization: `Bearer ${token}`, }, }); if (addressRes.ok) { const addresses = await addressRes.json(); const selectedAddress = localStorage.getItem("selectedAddress"); if (selectedAddress) { const parsedSelectedAddress = JSON.parse(selectedAddress); // 在服务器返回的地址列表中查找选中的地址 const matchedAddress = addresses.find( (addr) => addr._id === parsedSelectedAddress._id ); if (matchedAddress) { setAddress(matchedAddress); localStorage.removeItem("selectedAddress"); return; } } // 如果没有匹配到选中的地址,使用默认地址 const defaultAddress = addresses.find((addr) => addr.isDefault); if (defaultAddress) { setAddress(defaultAddress); } else if (addresses.length > 0) { setAddress(addresses[0]); } } }; // 获取商品信息的函数 const fetchProducts = async () => { const items = searchParams.get("items"); if (items) { const productPromises = items.split(",").map(async (item) => { const [productId, quantity] = item.split(":"); const res = await fetch(`/api/products/${productId}`); if (!res.ok) { throw new Error("获取商品信息失败"); } const product = await res.json(); return { ...product, quantity: parseInt(quantity) }; }); const productsData = await Promise.all(productPromises); setProducts(productsData); return; } const productId = searchParams.get("products"); const quantity = searchParams.get("quantity"); if (!productId || !quantity) { throw new Error("商品信息不完整"); } const res = await fetch(`/api/products/${productId}`); if (!res.ok) { throw new Error("获取商品信息失败"); } const product = await res.json(); setProducts([{ ...product, quantity: parseInt(quantity) }]); }; useEffect(() => { const token = localStorage.getItem("token"); if (!token) { router.push("/login"); return; } const fetchData = async () => { try { await fetchAddress(token); await fetchProducts(); } catch (err) { setError(err.message); } finally { setLoading(false); } }; fetchData(); }, []); if (loading) return