Krishya | e71688a | 2025-04-10 21:25:17 +0800 | [diff] [blame] | 1 | import React, { useState, useEffect } from 'react'; |
| 2 | import { useRoute } from 'wouter'; |
| 3 | import axios from 'axios'; |
| 4 | import './PostDetailPage.css'; |
| 5 | |
| 6 | const API_BASE = process.env.REACT_APP_API_BASE; |
| 7 | |
| 8 | const PostDetailPage = () => { |
| 9 | const [post, setPost] = useState(null); |
| 10 | const [loading, setLoading] = useState(true); |
| 11 | const [errorMsg, setErrorMsg] = useState(''); |
| 12 | |
| 13 | // 使用 wouter 的 useRoute 获取 postId 参数 |
| 14 | const { params } = useRoute('/forum/post/:postId'); |
| 15 | const postId = params?.postId; |
| 16 | |
| 17 | useEffect(() => { |
| 18 | const fetchPostDetail = async () => { |
| 19 | setLoading(true); |
| 20 | setErrorMsg(''); |
| 21 | try { |
| 22 | const response = await axios.get(`${API_BASE}/echo/forum/posts/${postId}`); |
| 23 | setPost(response.data); |
| 24 | } catch (error) { |
| 25 | console.error('获取帖子详情失败:', error); |
| 26 | setErrorMsg('加载失败,请稍后重试'); |
| 27 | } finally { |
| 28 | setLoading(false); |
| 29 | } |
| 30 | }; |
| 31 | |
| 32 | if (postId) { |
| 33 | fetchPostDetail(); |
| 34 | } |
| 35 | }, [postId]); |
| 36 | |
| 37 | if (loading) return <p>加载中...</p>; |
| 38 | if (errorMsg) return <p className="error-text">{errorMsg}</p>; |
| 39 | if (!post) return <p>没有找到该帖子。</p>; |
| 40 | |
| 41 | return ( |
| 42 | <div className="post-detail-page"> |
| 43 | <h2>{post.title}</h2> |
| 44 | <div className="post-meta"> |
| 45 | <span>作者:{post.userProfile.nickname}</span> |
| 46 | <span>发布时间:{new Date(post.created_at).toLocaleString()}</span> |
| 47 | </div> |
| 48 | <div className="post-content"> |
| 49 | <p>{post.content}</p> |
| 50 | </div> |
| 51 | {post.cover_image_url && ( |
| 52 | <div className="post-image"> |
| 53 | <img src={post.cover_image_url} alt="封面" /> |
| 54 | </div> |
| 55 | )} |
| 56 | </div> |
| 57 | ); |
| 58 | }; |
| 59 | |
| 60 | export default PostDetailPage; |