"use client"; import React, { useState, useEffect, Suspense } from "react"; import { useRouter, useSearchParams } from "next/navigation"; function AddressContent() { const router = useRouter(); const searchParams = useSearchParams(); const [addresses, setAddresses] = useState([]); const [showForm, setShowForm] = useState(false); const [formData, setFormData] = useState({ name: "", phone: "", address: "", isDefault: false, }); useEffect(() => { const token = localStorage.getItem("token"); if (!token) { router.push("/login"); return; } fetchAddresses(); }, [router]); const fetchAddresses = async () => { try { const res = await fetch("/api/address", { headers: { Authorization: `Bearer ${localStorage.getItem("token")}`, }, }); const data = await res.json(); setAddresses(data); } catch (error) { console.error("获取地址失败:", error); } }; const handleSelectAddress = (address) => { const returnUrl = searchParams.get("returnUrl"); const items = searchParams.get("items"); const products = searchParams.get("products"); const quantity = searchParams.get("quantity"); localStorage.setItem("selectedAddress", JSON.stringify(address)); if (returnUrl) { let finalUrl = returnUrl; if (items) { finalUrl += `?items=${items}`; } else if (products && quantity) { finalUrl += `?products=${products}&quantity=${quantity}`; } router.replace(finalUrl); } else { router.replace("/checkout"); } }; const handleSubmit = async (e) => { e.preventDefault(); try { const res = await fetch("/api/address", { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${localStorage.getItem("token")}`, }, body: JSON.stringify(formData), }); if (!res.ok) { throw new Error("添加地址失败"); } setShowForm(false); setFormData({ name: "", phone: "", address: "", isDefault: false }); await fetchAddresses(); } catch (error) { console.error("添加地址失败:", error); } }; return (
{address.address}
{address.isDefault && ( 默认地址 )}