"use client"; import { useState, useEffect } from "react"; import { useRouter } from "next/navigation"; import { fetchPostDetail, apiMe, apiUpdatePost, type Post, type User } from "@/lib/api"; interface EditPageProps { params: Promise<{ id: string }>; } export default function EditPostPage({ params }: EditPageProps) { const router = useRouter(); const [post, setPost] = useState(null); const [user, setUser] = useState(null); const [title, setTitle] = useState(""); const [content, setContent] = useState(""); const [tags, setTags] = useState(""); const [loading, setLoading] = useState(false); const [error, setError] = useState(""); const [checking, setChecking] = useState(true); // params 是 Promise,需要解包 const [id, setId] = useState(""); useEffect(() => { params.then((p) => setId(p.id)); }, [params]); // 加载帖子 + 校验权限 useEffect(() => { if (!id) return; Promise.all([fetchPostDetail(id), apiMe()]) .then(([postData, meData]) => { setPost(postData.post); setTitle(postData.post.title); setContent(postData.post.content); setTags(postData.post.tags || ""); const u = meData.user; setUser(u || null); // 非作者且非管理员 → 跳转 if (!u || (u.id !== postData.post.user.id && u.role !== "admin")) { router.push(`/post/${id}`); } }) .catch(() => router.push(`/post/${id}`)) .finally(() => setChecking(false)); }, [id, router]); const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); if (!post) return; setLoading(true); setError(""); try { const res = await apiUpdatePost(String(post.id), { title, content, tags }); if (res.post) { router.push(`/post/${post.id}`); } else { setError(res.error || "更新失败"); } } finally { setLoading(false); } }; if (checking) { return (
加载中...
); } if (!post) return null; return (

编辑帖子

{error && (
{error}
)}
setTitle(e.target.value)} required maxLength={256} className="w-full px-3 py-2 rounded-lg border" style={{ borderColor: "var(--border)", background: "var(--bg)", color: "var(--text)" }} />
setTags(e.target.value)} placeholder="例如:技术,Go" className="w-full px-3 py-2 rounded-lg border" style={{ borderColor: "var(--border)", background: "var(--bg)", color: "var(--text)" }} />