blob: 59d9c9a7350f296d87e7bcdf3d92c46e2fe6009a [file] [log] [blame]
2230100964011632025-06-04 21:57:22 +08001import React, { useEffect, useState } from 'react';
2import axios from 'axios';
3import Header from '../../components/Header';
4import UserNav from './UserNav';
5import { useUser } from '../../context/UserContext';
6import { useLocation } from 'wouter'; // ✅ 引入 wouter 的 useLocation
7import './UserCollect.css';
8
9const UserCollect = () => {
10 const { user, loading: userLoading } = useUser();
11 const [collections, setCollections] = useState([]);
12 const [loading, setLoading] = useState(true);
13 const [error, setError] = useState(null);
14 const [, navigate] = useLocation(); // ✅ 获取跳转函数
15
16 useEffect(() => {
17 if (userLoading) return;
18
19 if (!user || !user.userId) {
20 setError('未登录或用户信息获取失败');
21 setLoading(false);
22 return;
23 }
24
25 const fetchCollections = async () => {
26 try {
27 const response = await axios.get(`/echo/forum/posts/${user.userId}/getAllcollections`);
28 setCollections(response.data || []);
29 setError(null);
30 } catch (error) {
31 console.error('获取收藏失败:', error);
32 setError('获取收藏失败,请稍后再试');
33 } finally {
34 setLoading(false);
35 }
36 };
37
38 fetchCollections();
39 }, [user, userLoading]);
40
41 return (
42 <div className="user-profile-container">
43 <Header />
44 <div className="user-center">
45 <div className="user-nav-container">
46 <UserNav />
47 </div>
48
49 <div className="common-card">
50 <div className="right-content">
51 <h2 style={{ marginBottom: '1rem' }}>我的收藏</h2>
52 {userLoading || loading ? (
53 <p>加载中...</p>
54 ) : error ? (
55 <p className="error">{error}</p>
56 ) : collections.length === 0 ? (
57 <p>暂无收藏内容。</p>
58 ) : (
59 collections.map((post) => (
60 <div
61 key={post.postNo}
62 className="post-item"
63 onClick={() => navigate(`/forum/post/${post.postNo}`)} // ✅ 跳转帖子详情页
64 style={{ cursor: 'pointer' }}
65 >
66 <h3>{post.title || '无标题'}</h3>
67 <p>{post.postContent?.slice(0, 100) || '暂无内容'}...</p>
68 <p style={{ fontSize: '12px', color: '#888' }}>
69 作者:{post.username || '未知'} | 发布时间未知
70 </p>
71 <hr />
72 </div>
73 ))
74 )}
75 </div>
76 </div>
77 </div>
78 </div>
79 );
80};
81
82export default UserCollect;