| import React, { useEffect, useState } from 'react'; |
| import axios from 'axios'; |
| import Header from '../../components/Header'; |
| import UserNav from './UserNav'; |
| import { useUser } from '../../context/UserContext'; |
| import { useLocation } from 'wouter'; // ✅ 引入 wouter 的 useLocation |
| import './UserCollect.css'; |
| |
| const UserCollect = () => { |
| const { user, loading: userLoading } = useUser(); |
| const [collections, setCollections] = useState([]); |
| const [loading, setLoading] = useState(true); |
| const [error, setError] = useState(null); |
| const [, navigate] = useLocation(); // ✅ 获取跳转函数 |
| |
| useEffect(() => { |
| if (userLoading) return; |
| |
| if (!user || !user.userId) { |
| setError('未登录或用户信息获取失败'); |
| setLoading(false); |
| return; |
| } |
| |
| const fetchCollections = async () => { |
| try { |
| const response = await axios.get(`/echo/forum/posts/${user.userId}/getAllcollections`); |
| setCollections(response.data || []); |
| setError(null); |
| } catch (error) { |
| console.error('获取收藏失败:', error); |
| setError('获取收藏失败,请稍后再试'); |
| } finally { |
| setLoading(false); |
| } |
| }; |
| |
| fetchCollections(); |
| }, [user, userLoading]); |
| |
| return ( |
| <div className="user-profile-container"> |
| <Header /> |
| <div className="user-center"> |
| <div className="user-nav-container"> |
| <UserNav /> |
| </div> |
| |
| <div className="common-card"> |
| <div className="right-content"> |
| <h2 style={{ marginBottom: '1rem' }}>我的收藏</h2> |
| {userLoading || loading ? ( |
| <p>加载中...</p> |
| ) : error ? ( |
| <p className="error">{error}</p> |
| ) : collections.length === 0 ? ( |
| <p>暂无收藏内容。</p> |
| ) : ( |
| collections.map((post) => ( |
| <div |
| key={post.postNo} |
| className="post-item" |
| onClick={() => navigate(`/forum/post/${post.postNo}`)} // ✅ 跳转帖子详情页 |
| style={{ cursor: 'pointer' }} |
| > |
| <h3>{post.title || '无标题'}</h3> |
| <p>{post.postContent?.slice(0, 100) || '暂无内容'}...</p> |
| <p style={{ fontSize: '12px', color: '#888' }}> |
| 作者:{post.username || '未知'} | 发布时间未知 |
| </p> |
| <hr /> |
| </div> |
| )) |
| )} |
| </div> |
| </div> |
| </div> |
| </div> |
| ); |
| }; |
| |
| export default UserCollect; |