更新论坛功能
Change-Id: I0efd26d35cc4abb0c6d51ff1bff2cfd738f986dd
diff --git a/src/pages/Forum/ForumPage.jsx b/src/pages/Forum/ForumPage.jsx
deleted file mode 100644
index f51e679..0000000
--- a/src/pages/Forum/ForumPage.jsx
+++ /dev/null
@@ -1,148 +0,0 @@
-import React, { useState, useEffect } from 'react';
-import { Link } from 'wouter';
-import axios from 'axios';
-import { GoodTwo, Comment } from '@icon-park/react';
-import Header from '../../components/Header';
-import './ForumPage.css';
-
-const API_BASE = process.env.REACT_APP_API_BASE;
-
-const ForumPage = () => {
- const [posts, setPosts] = useState([]);
- const [total, setTotal] = useState(0);
- const [page, setPage] = useState(1);
- const [size, setSize] = useState(10);
- const [loading, setLoading] = useState(true);
- const [errorMsg, setErrorMsg] = useState('');
-
- const totalPages = Math.ceil(total / size);
-
- useEffect(() => {
- const fetchPosts = async () => {
- setLoading(true);
- setErrorMsg('');
- try {
- const response = await axios.get(`${API_BASE}/echo/forum/posts/getAllPost`, {
- params: { page, size }
- });
- const postsData = response.data.posts || [];
-
- const userIds = [...new Set(postsData.map(post => post.user_id))];
- const userProfiles = await Promise.all(
- userIds.map(async id => {
- try {
- const res = await axios.get(`${API_BASE}/echo/user/profile`, {
- params: { user_id: id }
- });
- return { id, profile: res.data };
- } catch {
- return { id, profile: { nickname: '未知用户', avatar_url: 'default-avatar.png' } };
- }
- })
- );
-
- const userMap = {};
- userProfiles.forEach(({ id, profile }) => {
- userMap[id] = profile;
- });
-
- const postsWithProfiles = postsData.map(post => ({
- ...post,
- userProfile: userMap[post.user_id] || { nickname: '未知用户', avatar_url: 'default-avatar.png' }
- }));
-
- setPosts(postsWithProfiles);
- setTotal(response.data.total || 0);
- } catch (error) {
- console.error('获取帖子失败:', error);
- setErrorMsg('加载失败,请稍后重试');
- } finally {
- setLoading(false);
- }
- };
- fetchPosts();
- }, [page, size]);
-
- const toggleLike = async (postId, liked) => {
- try {
- if (liked) {
- await axios.delete(`${API_BASE}/echo/forum/posts/${postId}/unlike`);
- } else {
- await axios.post(`${API_BASE}/echo/forum/posts/${postId}/like`);
- }
-
- setPosts(prevPosts =>
- prevPosts.map(post =>
- post.id === postId
- ? {
- ...post,
- liked: !liked,
- likeCount: liked ? post.likeCount - 1 : post.likeCount + 1
- }
- : post
- )
- );
- } catch (error) {
- console.error('点赞操作失败:', error);
- }
- };
-
- return (
- <div className="forum-page">
- <Header /> {/* 使用 Header 组件 */}
- <div className="forum-content">
- <h2>论坛帖子列表</h2>
-
- {loading ? (
- <p>加载中...</p>
- ) : errorMsg ? (
- <p className="error-text">{errorMsg}</p>
- ) : posts.length === 0 ? (
- <p>暂无帖子。</p>
- ) : (
- <div className="post-list">
- {posts.map(post => (
- <div key={post.id} className="post-card">
- <div className="post-card-top">
- <div className="user-info">
- <img className="avatar" src={post.userProfile.avatar_url} alt="头像" />
- <span className="nickname">{post.userProfile.nickname}</span>
- </div>
- {post.cover_image_url && (
- <img className="cover-image" src={post.cover_image_url} alt="封面" />
- )}
- </div>
- <h3>{post.title}</h3>
- <p className="post-meta">
- 发布时间:{new Date(post.created_at).toLocaleString()}
- </p>
- <div className="post-actions">
- <button
- className="icon-btn"
- onClick={() => toggleLike(post.id, post.liked)}
- >
- <GoodTwo theme="outline" size="24" fill={post.liked ? '#f00' : '#fff'} />
- <span>{post.likeCount || 0}</span>
- </button>
- <Link href={`/forum/post/${post.id}`} className="icon-btn">
- <Comment theme="outline" size="24" fill="#fff" />
- <span>{post.commentCount || 0}</span>
- </Link>
- </div>
- <Link href={`/forum/post/${post.id}`} className="btn-secondary">查看详情</Link>
- </div>
- ))}
- </div>
- )}
-
- <div className="pagination">
- <button disabled={page === 1} onClick={() => setPage(page - 1)}>上一页</button>
- <span>第 {page} 页 / 共 {totalPages} 页</span>
- <button disabled={page === totalPages} onClick={() => setPage(page + 1)}>下一页</button>
- </div>
- </div>
- </div>
- );
-};
-
-export default ForumPage;
diff --git a/src/pages/Forum/PostDetail.jsx b/src/pages/Forum/PostDetail.jsx
deleted file mode 100644
index f7067bf..0000000
--- a/src/pages/Forum/PostDetail.jsx
+++ /dev/null
@@ -1,29 +0,0 @@
-import React, { useState, useEffect } from'react';
-import axios from 'axios';
-
-const PostDetail = ({ post_id }) => {
- const [post, setPost] = useState({});
-
- useEffect(() => {
- const fetchPost = async () => {
- try {
- const response = await axios.get(`/echo/forum/posts/${post_id}`);
- setPost(response.data);
- } catch (error) {
- console.error('Error fetching post detail:', error);
- }
- };
- fetchPost();
- }, [post_id]);
-
- return (
- <div>
- <h1>{post.title}</h1>
- <p>作者: {post.author}</p>
- <p>内容: {post.Postcontent}</p>
- {post.imgUrl && <img src={post.imgUrl} alt={post.title} />}
- </div>
- );
-};
-
-export default PostDetail;
\ No newline at end of file
diff --git a/src/pages/Forum/PostDetailPage.jsx b/src/pages/Forum/PostDetailPage.jsx
deleted file mode 100644
index 6cdabd6..0000000
--- a/src/pages/Forum/PostDetailPage.jsx
+++ /dev/null
@@ -1,60 +0,0 @@
-import React, { useState, useEffect } from 'react';
-import { useRoute } from 'wouter';
-import axios from 'axios';
-import './PostDetailPage.css';
-
-const API_BASE = process.env.REACT_APP_API_BASE;
-
-const PostDetailPage = () => {
- const [post, setPost] = useState(null);
- const [loading, setLoading] = useState(true);
- const [errorMsg, setErrorMsg] = useState('');
-
- // 使用 wouter 的 useRoute 获取 postId 参数
- const { params } = useRoute('/forum/post/:postId');
- const postId = params?.postId;
-
- useEffect(() => {
- const fetchPostDetail = async () => {
- setLoading(true);
- setErrorMsg('');
- try {
- const response = await axios.get(`${API_BASE}/echo/forum/posts/${postId}`);
- setPost(response.data);
- } catch (error) {
- console.error('获取帖子详情失败:', error);
- setErrorMsg('加载失败,请稍后重试');
- } finally {
- setLoading(false);
- }
- };
-
- if (postId) {
- fetchPostDetail();
- }
- }, [postId]);
-
- if (loading) return <p>加载中...</p>;
- if (errorMsg) return <p className="error-text">{errorMsg}</p>;
- if (!post) return <p>没有找到该帖子。</p>;
-
- return (
- <div className="post-detail-page">
- <h2>{post.title}</h2>
- <div className="post-meta">
- <span>作者:{post.userProfile.nickname}</span>
- <span>发布时间:{new Date(post.created_at).toLocaleString()}</span>
- </div>
- <div className="post-content">
- <p>{post.content}</p>
- </div>
- {post.cover_image_url && (
- <div className="post-image">
- <img src={post.cover_image_url} alt="封面" />
- </div>
- )}
- </div>
- );
-};
-
-export default PostDetailPage;
diff --git a/src/pages/Forum/posts-create/CreatePost.css b/src/pages/Forum/posts-create/CreatePost.css
new file mode 100644
index 0000000..7707a0c
--- /dev/null
+++ b/src/pages/Forum/posts-create/CreatePost.css
@@ -0,0 +1,64 @@
+.create-post-page {
+ display: flex;
+ flex-direction: column;
+ padding: 20px;
+ gap: 20px;
+ }
+
+ .title-and-button {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ }
+
+ .title-input {
+ flex: 1;
+ height: 40px;
+ padding: 0 10px;
+ font-size: 16px;
+ }
+
+ .submit-button {
+ height: 40px;
+ padding: 0 20px;
+ font-size: 16px;
+ background-color: #409eff;
+ color: white;
+ border: none;
+ border-radius: 4px;
+ }
+
+ .layout {
+ display: flex;
+ gap: 20px;
+ }
+
+ .main-content {
+ flex: 3;
+ }
+
+ .content-editor {
+ width: 100%;
+ height: 650px;
+ padding: 10px;
+ font-size: 16px;
+ border: 1px solid #ccc;
+ }
+
+ .sidebar-content {
+ flex: 1;
+ display: flex;
+ flex-direction: column;
+ gap: 20px;
+ }
+
+ .sidebar-section {
+ background: #f9f9f9;
+ padding: 10px;
+ border-radius: 6px;
+ }
+
+ .sidebar-section p {
+ margin: 0 0 10px 0;
+ }
+
\ No newline at end of file
diff --git a/src/pages/Forum/CreatePost.jsx b/src/pages/Forum/posts-create/CreatePost.jsx
similarity index 66%
rename from src/pages/Forum/CreatePost.jsx
rename to src/pages/Forum/posts-create/CreatePost.jsx
index 1ac2d84..a03a836 100644
--- a/src/pages/Forum/CreatePost.jsx
+++ b/src/pages/Forum/posts-create/CreatePost.jsx
@@ -2,10 +2,13 @@
import React, { useState } from 'react';
import axios from 'axios';
+const API_BASE = process.env.REACT_APP_API_BASE;
+
const CreatePost = ({ userId }) => {
const [title, setTitle] = useState('');
const [content, setContent] = useState('');
- const [imageUrl, setImageUrl] = useState('');
+ const [imgUrl, setImageUrl] = useState('');
+ const [isAnonymous, setIsAnonymous] = useState(false);
const handleSubmit = async (e) => {
e.preventDefault();
@@ -13,29 +16,31 @@
try {
const postData = {
title,
- Postcontent: content,
+ postContent: content,
+ postType: isAnonymous,
};
- if (imageUrl.trim()) {
- postData.imgerrul = imageUrl;
+ if (imgUrl.trim()) {
+ postData.imgUrl = imgUrl;
}
const response = await axios.post(
- `/echo/forum/posts/${userId}/creatPost`,
+ `${API_BASE}/echo/forum/posts/${userId}/createPost`,
postData
);
+
if (response.status === 201) {
alert('帖子创建成功!');
- // 清空表单或跳转页面
setTitle('');
setContent('');
setImageUrl('');
+ setIsAnonymous(false);
}
} catch (error) {
- console.error('帖子创建失败:', error);
+ console.error('帖子创建失败:', error.response?.data || error.message);
alert('创建失败,请重试');
- }
+ }
};
return (
@@ -63,14 +68,24 @@
<label>图片 URL(可选):</label>
<input
type="text"
- value={imageUrl}
+ value={imgUrl}
onChange={(e) => setImageUrl(e.target.value)}
/>
</div>
+ <div>
+ <label>
+ <input
+ type="checkbox"
+ checked={isAnonymous}
+ onChange={(e) => setIsAnonymous(e.target.checked)}
+ />
+ 匿名发布
+ </label>
+ </div>
<button type="submit">发布</button>
</form>
</div>
);
};
-export default CreatePost;
+export default CreatePost;
\ No newline at end of file
diff --git a/src/pages/Forum/posts-create/CreatePostPage.jsx b/src/pages/Forum/posts-create/CreatePostPage.jsx
new file mode 100644
index 0000000..ea2505c
--- /dev/null
+++ b/src/pages/Forum/posts-create/CreatePostPage.jsx
@@ -0,0 +1,11 @@
+// src/pages/Forum/posts-create/CreatePostPage.jsx
+import React from 'react';
+import { useUserStore } from '../../store/user';
+import CreatePost from './CreatePost';
+
+const CreatePostPage = () => {
+ const { user } = useUserStore(); // 拿到 user
+ return <CreatePost userId={user?.id} />;
+};
+
+export default CreatePostPage;
diff --git a/src/pages/Forum/PostDetailPage.css b/src/pages/Forum/posts-detail/PostDetailPage.css
similarity index 100%
rename from src/pages/Forum/PostDetailPage.css
rename to src/pages/Forum/posts-detail/PostDetailPage.css
diff --git a/src/pages/Forum/posts-detail/PostDetailPage.jsx b/src/pages/Forum/posts-detail/PostDetailPage.jsx
new file mode 100644
index 0000000..c0f218f
--- /dev/null
+++ b/src/pages/Forum/posts-detail/PostDetailPage.jsx
@@ -0,0 +1,310 @@
+import React, { useState, useEffect } from 'react';
+import { useRoute } from 'wouter';
+import {
+ getPostDetail,
+ getPostComments,
+ likePost,
+ unlikePost,
+ addCommentToPost,
+ replyToComment,
+ likeComment,
+ unlikeComment,
+ getUserInfo
+} from './api';
+import './PostDetailPage.css';
+import axios from 'axios';
+
+const API_BASE = process.env.REACT_APP_API_BASE;
+
+const PostHeader = ({ post }) => {
+ const anonymousAvatar = '/assets/img/anonymous.jpg';
+ return (
+ <div className="post-header">
+ <div className="author-info">
+ <img className="avatar" src={post.isAnonymous? anonymousAvatar : post.userProfile.avatar_url} alt="头像" />
+ <span className="author-name">{post.isAnonymous? '某同学' : post.userProfile.nickname}</span>
+ </div>
+ <h1 className="post-title">{post.title}</h1>
+ </div>
+ );
+};
+
+const PostContent = ({ content }) => {
+ return (
+ <div className="post-content" dangerouslySetInnerHTML={{ __html: content }} />
+ );
+};
+
+const PostActions = ({ post, onLike, onFavorite }) => {
+ return (
+ <div className="post-actions">
+ <div className="action-item" onClick={onLike}>
+ <i className={post.liked? 'liked' : 'unliked'} />
+ <span>{post.likeCount || 0}</span>
+ </div>
+ <div className="action-item" onClick={onFavorite}>
+ <i className={post.favorited? 'favorited' : 'unfavorited'} />
+ <span>{post.favorites || 0}</span>
+ </div>
+ </div>
+ );
+};
+
+const CommentInput = ({ onSubmitComment, isFlag }) => {
+ const [content, setContent] = useState('');
+
+ useEffect(() => {
+ if (isFlag) {
+ setContent('');
+ }
+ }, [isFlag]);
+
+ const handleSubmit = () => {
+ if (content) {
+ onSubmitComment(content);
+ }
+ };
+
+ return (
+ <div className="comment-input">
+ <textarea
+ value={content}
+ onChange={(e) => setContent(e.target.value)}
+ placeholder="写下你的评论..."
+ className="comment-textarea"
+ />
+ <div className="button-container">
+ <button
+ type="button"
+ onClick={handleSubmit}
+ disabled={!content}
+ className="submit-button"
+ >
+ 发布评论
+ </button>
+ </div>
+ </div>
+ );
+};
+
+const CommentItem = ({ comment, onLikeComment, onReplyComment }) => {
+ const [showReplyInput, setShowReplyInput] = useState(false);
+ const [replyContent, setReplyContent] = useState('');
+
+ const queryUserInfo = async (id) => {
+ if (!id) {
+ return;
+ }
+ try {
+ const userData = await getUserInfo(id);
+ console.log(userData);
+ // 这里可以添加跳转逻辑等,比如根据用户ID跳转到对应个人信息页面
+ } catch (error) {
+ console.error('获取用户信息失败:', error);
+ }
+ };
+
+ const handleLike = () => {
+ onLikeComment(comment);
+ };
+
+ const handleReply = () => {
+ setShowReplyInput(!showReplyInput);
+ };
+
+ const handleSubmitReply = () => {
+ if (replyContent) {
+ onReplyComment(comment, replyContent);
+ setReplyContent('');
+ setShowReplyInput(false);
+ }
+ };
+
+ return (
+ <div className="comment-item">
+ <img className="avatar" src={comment.author.avatar_url} alt="头像" onClick={() => queryUserInfo(comment.author.userId)} />
+ <div className="comment-content">
+ <div className="comment-author">{comment.author.nickname}</div>
+ <div className="comment-text">{comment.content}</div>
+ <div className="comment-actions">
+ <div className="action-item" onClick={handleLike}>
+ <i className={comment.liked? 'liked' : 'unliked'} />
+ <span>{comment.likeCount || 0}</span>
+ </div>
+ <button type="button" onClick={handleReply}>回复</button>
+ </div>
+ {showReplyInput && (
+ <div className="reply-input">
+ <textarea
+ value={replyContent}
+ onChange={(e) => setReplyContent(e.target.value)}
+ placeholder="写下你的回复..."
+ className="reply-textarea"
+ />
+ <button
+ type="button"
+ onClick={handleSubmitReply}
+ disabled={!replyContent}
+ className="submit-button"
+ >
+ 发布回复
+ </button>
+ </div>
+ )}
+ {comment.replies && comment.replies.length > 0 && (
+ <div className="reply-list">
+ {comment.replies.map(reply => (
+ <CommentItem
+ key={reply.id}
+ comment={reply}
+ onLikeComment={onLikeComment}
+ onReplyComment={onReplyComment}
+ />
+ ))}
+ </div>
+ )}
+ </div>
+ </div>
+ );
+};
+
+const CommentsList = ({ comments, onLikeComment, onReplyComment }) => {
+ return (
+ <div className="comments-list">
+ <h2>评论</h2>
+ {comments.map(comment => (
+ <CommentItem
+ key={comment.id}
+ comment={comment}
+ onLikeComment={onLikeComment}
+ onReplyComment={onReplyComment}
+ />
+ ))}
+ </div>
+ );
+};
+
+const PostDetailPage = () => {
+ const [post, setPost] = useState(null);
+ const [loading, setLoading] = useState(true);
+ const [errorMsg, setErrorMsg] = useState('');
+ const [comments, setComments] = useState([]);
+ const [isFlag, setIsFlag] = useState(false);
+
+ const { params } = useRoute('/forum/post/:postId');
+ const postId = params?.postId;
+
+ useEffect(() => {
+ const fetchPostDetail = async () => {
+ setLoading(true);
+ setErrorMsg('');
+ try {
+ const postDetail = await getPostDetail(postId);
+ const postComments = await getPostComments(postId);
+ setPost(postDetail);
+ setComments(postComments);
+ } catch (error) {
+ console.error('获取帖子详情失败:', error);
+ setErrorMsg('加载失败,请稍后重试');
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ if (postId) {
+ fetchPostDetail();
+ }
+ }, [postId]);
+
+ const handleLike = async () => {
+ if (!post.liked) {
+ try {
+ await likePost(postId);
+ const newPost = { ...post, liked: true, likeCount: post.likeCount + 1 };
+ setPost(newPost);
+ } catch (err) {
+ console.error('点赞失败:', err);
+ }
+ } else {
+ try {
+ await unlikePost(postId);
+ const newPost = { ...post, liked: false, likeCount: post.likeCount - 1 };
+ setPost(newPost);
+ } catch (err) {
+ console.error('取消点赞失败:', err);
+ }
+ }
+ };
+
+ const handleFavorite = () => {
+ const newPost = { ...post, favorited: !post.favorited, favorites: post.favorited? post.favorites - 1 : post.favorites + 1 };
+ setPost(newPost);
+ if (newPost.favorited) {
+ axios.post(`${API_BASE}/echo/forum/posts/${postId}/favorite`).catch(err => {
+ console.error('收藏失败:', err);
+ });
+ } else {
+ axios.delete(`${API_BASE}/echo/forum/posts/${postId}/unfavorite`).catch(err => {
+ console.error('取消收藏失败:', err);
+ });
+ }
+ };
+
+ const likeCommentAction = async (comment) => {
+ if (!comment.liked) {
+ try {
+ await likeComment(comment.id);
+ const newComment = { ...comment, liked: true, likeCount: comment.likeCount + 1 };
+ setComments(comments.map(c => c.id === comment.id? newComment : c));
+ } catch (err) {
+ console.error('点赞评论失败:', err);
+ }
+ } else {
+ try {
+ await unlikeComment(comment.id);
+ const newComment = { ...comment, liked: false, likeCount: comment.likeCount - 1 };
+ setComments(comments.map(c => c.id === comment.id? newComment : c));
+ } catch (err) {
+ console.error('取消点赞评论失败:', err);
+ }
+ }
+ };
+
+ const replyCommentAction = async (comment, replyContent) => {
+ try {
+ await replyToComment(comment.id, replyContent);
+ setIsFlag(true);
+ const commentResponse = await getPostComments(postId);
+ setComments(commentResponse.data);
+ } catch (error) {
+ console.error('回复评论失败:', error);
+ }
+ };
+
+ const addCommentAction = async (content) => {
+ try {
+ await addCommentToPost(postId, content);
+ setIsFlag(true);
+ const commentResponse = await getPostComments(postId);
+ setComments(commentResponse.data);
+ } catch (error) {
+ console.error('添加评论失败:', error);
+ }
+ };
+
+ if (loading) return <p>加载中...</p>;
+ if (errorMsg) return <p className="error-text">{errorMsg}</p>;
+ if (!post) return <p>没有找到该帖子。</p>;
+
+ return (
+ <div className="post-detail-page">
+ <PostHeader post={post} />
+ <PostContent content={post.content} />
+ <PostActions post={post} onLike={handleLike} onFavorite={handleFavorite} />
+ <CommentInput onSubmitComment={addCommentAction} isFlag={isFlag} />
+ <CommentsList comments={comments} onLikeComment={likeCommentAction} onReplyComment={replyCommentAction} />
+ </div>
+ );
+};
+
+export default PostDetailPage;
\ No newline at end of file
diff --git a/src/pages/Forum/posts-detail/api.js b/src/pages/Forum/posts-detail/api.js
new file mode 100644
index 0000000..924cba9
--- /dev/null
+++ b/src/pages/Forum/posts-detail/api.js
@@ -0,0 +1,57 @@
+import axios from 'axios';
+
+const API_BASE = process.env.REACT_APP_API_BASE;
+
+// 获取帖子详情
+export const getPostDetail = async (postId) => {
+ const response = await axios.get(`${API_BASE}/echo/forum/posts/${postId}/getPost`);
+ return response.data;
+};
+
+// 获取帖子评论
+export const getPostComments = async (postId) => {
+ const response = await axios.get(`${API_BASE}/echo/forum/posts/${postId}/getAllComments`);
+ return response.data;
+};
+
+// 点赞帖子
+export const likePost = async (postId) => {
+ const response = await axios.post(`${API_BASE}/echo/forum/posts/${postId}/like`);
+ return response.data;
+};
+
+// 取消点赞帖子
+export const unlikePost = async (postId) => {
+ const response = await axios.delete(`${API_BASE}/echo/forum/posts/${postId}/unlike`);
+ return response.data;
+};
+
+// 添加评论
+export const addCommentToPost = async (postId, content) => {
+ const response = await axios.post(`${API_BASE}/echo/forum/posts/${postId}/comments`, { content });
+ return response.data;
+};
+
+// 回复评论
+export const replyToComment = async (commentId, replyContent) => {
+ const response = await axios.post(`${API_BASE}/echo/forum/comments/${commentId}/reply`, { content: replyContent });
+ return response.data;
+};
+
+// 点赞评论
+export const likeComment = async (commentId) => {
+ const response = await axios.post(`${API_BASE}/echo/forum/comments/${commentId}/like`);
+ return response.data;
+};
+
+// 取消点赞评论
+export const unlikeComment = async (commentId) => {
+ const response = await axios.delete(`${API_BASE}/echo/forum/comments/${commentId}/unlike`);
+ return response.data;
+};
+
+// 获取用户信息
+export const getUserInfo = async (userId) => {
+ const response = await axios.get(`${API_BASE}/user/${userId}/info`);
+ return response.data;
+};
\ No newline at end of file
diff --git a/src/pages/Forum/ForumPage.css b/src/pages/Forum/posts-main/ForumPage.css
similarity index 100%
rename from src/pages/Forum/ForumPage.css
rename to src/pages/Forum/posts-main/ForumPage.css
diff --git a/src/pages/Forum/posts-main/ForumPage.jsx b/src/pages/Forum/posts-main/ForumPage.jsx
new file mode 100644
index 0000000..5c7d622
--- /dev/null
+++ b/src/pages/Forum/posts-main/ForumPage.jsx
@@ -0,0 +1,177 @@
+// import React, { useState, useEffect } from 'react';
+// import { Link } from 'wouter';
+// import axios from 'axios';
+// import { GoodTwo, Comment } from '@icon-park/react';
+// import Header from '../../components/Header';
+// import './ForumPage.css';
+
+// const API_BASE = process.env.REACT_APP_API_BASE;
+
+// const ForumPage = () => {
+// const [posts, setPosts] = useState([]);
+// const [total, setTotal] = useState(0);
+// const [page, setPage] = useState(1);
+// const [size, setSize] = useState(10);
+// const [loading, setLoading] = useState(true);
+// const [errorMsg, setErrorMsg] = useState('');
+
+// const totalPages = Math.ceil(total / size);
+
+// useEffect(() => {
+// const fetchPosts = async () => {
+// setLoading(true);
+// setErrorMsg('');
+// try {
+// const response = await axios.get(`${API_BASE}/echo/forum/posts/getAllPost`, {
+// params: { page, size }
+// });
+// const postsData = response.data.posts || [];
+
+// const userIds = [...new Set(postsData.map(post => post.user_id))];
+// const userProfiles = await Promise.all(
+// userIds.map(async id => {
+// try {
+// const res = await axios.get(`${API_BASE}/echo/user/profile`, {
+// params: { user_id: id }
+// });
+// return { id, profile: res.data };
+// } catch {
+// return { id, profile: { nickname: '未知用户', avatar_url: 'default-avatar.png' } };
+// }
+// })
+// );
+
+// const userMap = {};
+// userProfiles.forEach(({ id, profile }) => {
+// userMap[id] = profile;
+// });
+
+// const postsWithProfiles = postsData.map(post => ({
+// ...post,
+// userProfile: userMap[post.user_id] || { nickname: '未知用户', avatar_url: 'default-avatar.png' }
+// }));
+
+// setPosts(postsWithProfiles);
+// setTotal(response.data.total || 0);
+// } catch (error) {
+// console.error('获取帖子失败:', error);
+// setErrorMsg('加载失败,请稍后重试');
+// } finally {
+// setLoading(false);
+// }
+// };
+// fetchPosts();
+// }, [page, size]);
+
+// const toggleLike = async (postId, liked) => {
+// try {
+// if (liked) {
+// await axios.delete(`${API_BASE}/echo/forum/posts/${postId}/unlike`);
+// } else {
+// await axios.post(`${API_BASE}/echo/forum/posts/${postId}/like`);
+// }
+
+// setPosts(prevPosts =>
+// prevPosts.map(post =>
+// post.id === postId
+// ? {
+// ...post,
+// liked: !liked,
+// likeCount: liked ? post.likeCount - 1 : post.likeCount + 1
+// }
+// : post
+// )
+// );
+// } catch (error) {
+// console.error('点赞操作失败:', error);
+// }
+// };
+
+// return (
+// <div className="forum-page">
+// <Header /> {/* 使用 Header 组件 */}
+// <div className="forum-content">
+// <h2>论坛帖子列表</h2>
+
+// {loading ? (
+// <p>加载中...</p>
+// ) : errorMsg ? (
+// <p className="error-text">{errorMsg}</p>
+// ) : posts.length === 0 ? (
+// <p>暂无帖子。</p>
+// ) : (
+// <div className="post-list">
+// {posts.map(post => (
+// <div key={post.id} className="post-card">
+// <div className="post-card-top">
+// <div className="user-info">
+// <img className="avatar" src={post.userProfile.avatar_url} alt="头像" />
+// <span className="nickname">{post.userProfile.nickname}</span>
+// </div>
+// {post.cover_image_url && (
+// <img className="cover-image" src={post.cover_image_url} alt="封面" />
+// )}
+// </div>
+// <h3>{post.title}</h3>
+// <p className="post-meta">
+// 发布时间:{new Date(post.created_at).toLocaleString()}
+// </p>
+// <div className="post-actions">
+// <button
+// className="icon-btn"
+// onClick={() => toggleLike(post.id, post.liked)}
+// >
+// <GoodTwo theme="outline" size="24" fill={post.liked ? '#f00' : '#fff'} />
+// <span>{post.likeCount || 0}</span>
+// </button>
+// <Link href={`/forum/post/${post.id}`} className="icon-btn">
+// <Comment theme="outline" size="24" fill="#fff" />
+// <span>{post.commentCount || 0}</span>
+// </Link>
+// </div>
+// <Link href={`/forum/post/${post.id}`} className="btn-secondary">查看详情</Link>
+// </div>
+// ))}
+// </div>
+// )}
+
+// <div className="pagination">
+// <button disabled={page === 1} onClick={() => setPage(page - 1)}>上一页</button>
+// <span>第 {page} 页 / 共 {totalPages} 页</span>
+// <button disabled={page === totalPages} onClick={() => setPage(page + 1)}>下一页</button>
+// </div>
+// </div>
+// </div>
+// );
+// };
+
+// export default ForumPage;
+
+import React, { useState } from 'react';
+import Header from '../../../components/Header';
+import SearchBar from './components/SearchBar';
+import CreatePostButton from './components/CreatePostButton';
+import PostList from './components/PostList';
+import './ForumPage.css';
+
+const ForumPage = () => {
+ const [searchQuery, setSearchQuery] = useState('');
+
+ const handleSearch = (query) => {
+ setSearchQuery(query);
+ };
+
+ return (
+ <div className="forum-page">
+ <Header />
+ <div className="toolbar">
+ <SearchBar onSearch={handleSearch} />
+ <CreatePostButton />
+ </div>
+ <PostList search={searchQuery} />
+ </div>
+ );
+};
+
+export default ForumPage;
+
diff --git a/src/pages/Forum/posts-main/components/CreatePostButton.css b/src/pages/Forum/posts-main/components/CreatePostButton.css
new file mode 100644
index 0000000..c118c7a
--- /dev/null
+++ b/src/pages/Forum/posts-main/components/CreatePostButton.css
@@ -0,0 +1,11 @@
+.create-post {
+ display: flex;
+ justify-content: center;
+ margin: 20px 0;
+ }
+
+ .create-post-button {
+ display: flex;
+ align-items: center;
+ }
+
\ No newline at end of file
diff --git a/src/pages/Forum/posts-main/components/CreatePostButton.jsx b/src/pages/Forum/posts-main/components/CreatePostButton.jsx
new file mode 100644
index 0000000..0632173
--- /dev/null
+++ b/src/pages/Forum/posts-main/components/CreatePostButton.jsx
@@ -0,0 +1,22 @@
+import React from 'react';
+import { useLocation } from 'wouter';
+import { Edit } from '@icon-park/react';
+import './CreatePostButton.css';
+
+const CreatePostButton = () => {
+ const [, navigate] = useLocation();
+
+ const goToCreatePost = () => {
+ navigate('/forum/create-post');
+ };
+
+ return (
+ <div className="create-post">
+ <button onClick={goToCreatePost} className="create-btn">
+ <Edit theme="outline" size="18" /> 发帖
+ </button>
+ </div>
+ );
+};
+
+export default CreatePostButton;
diff --git a/src/pages/Forum/posts-main/components/PostList.css b/src/pages/Forum/posts-main/components/PostList.css
new file mode 100644
index 0000000..d855c07
--- /dev/null
+++ b/src/pages/Forum/posts-main/components/PostList.css
@@ -0,0 +1,12 @@
+.post-list {
+ display: flex;
+ flex-direction: column;
+ gap: 16px;
+ }
+
+ .post-card {
+ border: 1px solid #eee;
+ padding: 16px;
+ border-radius: 8px;
+ }
+
\ No newline at end of file
diff --git a/src/pages/Forum/posts-main/components/PostList.jsx b/src/pages/Forum/posts-main/components/PostList.jsx
new file mode 100644
index 0000000..fa33dd5
--- /dev/null
+++ b/src/pages/Forum/posts-main/components/PostList.jsx
@@ -0,0 +1,126 @@
+import React, { useEffect, useState } from 'react';
+import axios from 'axios';
+import { Link } from 'wouter';
+import { GoodTwo, Comment } from '@icon-park/react';
+import './PostList.css';
+
+const API_BASE = process.env.REACT_APP_API_BASE;
+
+const PostList = ({ search }) => {
+ const [posts, setPosts] = useState([]);
+ const [page, setPage] = useState(1);
+ const [total, setTotal] = useState(0);
+ const [loading, setLoading] = useState(true);
+ const [errorMsg, setErrorMsg] = useState('');
+
+ const size = 10;
+ const totalPages = Math.ceil(total / size);
+
+ useEffect(() => {
+ const fetchPosts = async () => {
+ setLoading(true);
+ setErrorMsg('');
+ try {
+ const res = await axios.get(`${API_BASE}/echo/forum/posts/getAllPost`, {
+ params: { page, size }
+ });
+
+ const postsData = res.data.posts || [];
+ const userIds = [...new Set(postsData.map(p => p.user_id))];
+
+ const profiles = await Promise.all(userIds.map(async id => {
+ try {
+ const r = await axios.get(`${API_BASE}/echo/user/profile`, {
+ params: { user_id: id }
+ });
+ return { id, profile: r.data };
+ } catch {
+ return { id, profile: { nickname: '未知用户', avatar_url: 'default-avatar.png' } };
+ }
+ }));
+
+ const userMap = {};
+ profiles.forEach(({ id, profile }) => { userMap[id] = profile; });
+
+ const postsWithProfiles = postsData
+ .filter(post => post.title.includes(search))
+ .map(post => ({
+ ...post,
+ userProfile: userMap[post.user_id] || {}
+ }));
+
+ setPosts(postsWithProfiles);
+ setTotal(res.data.total || 0);
+ } catch (err) {
+ console.error('加载失败:', err);
+ setErrorMsg('加载失败,请稍后重试');
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ fetchPosts();
+ }, [page, search]);
+
+ const toggleLike = async (postId, liked) => {
+ try {
+ if (liked) await axios.delete(`${API_BASE}/echo/forum/posts/${postId}/unlike`);
+ else await axios.post(`${API_BASE}/echo/forum/posts/${postId}/like`);
+
+ setPosts(posts =>
+ posts.map(post =>
+ post.id === postId
+ ? { ...post, liked: !liked, likeCount: liked ? post.likeCount - 1 : post.likeCount + 1 }
+ : post
+ )
+ );
+ } catch (err) {
+ console.error('点赞失败:', err);
+ }
+ };
+
+ return (
+ <div className="post-list">
+ {loading ? <p>加载中...</p> :
+ errorMsg ? <p className="error-text">{errorMsg}</p> :
+ posts.length === 0 ? <p>暂无帖子。</p> :
+ posts.map(post => (
+ <div key={post.id} className="post-card">
+ <div className="post-card-top">
+ <div className="user-info">
+ <img className="avatar" src={post.userProfile.avatar_url} alt="头像" />
+ <span className="nickname">{post.userProfile.nickname}</span>
+ </div>
+ {post.cover_image_url && (
+ <img className="cover-image" src={post.cover_image_url} alt="封面" />
+ )}
+ </div>
+ <h3>{post.title}</h3>
+ <p className="post-meta">
+ 发布时间:{new Date(post.created_at).toLocaleString()}
+ </p>
+ <div className="post-actions">
+ <button className="icon-btn" onClick={() => toggleLike(post.id, post.liked)}>
+ <GoodTwo theme="outline" size="24" fill={post.liked ? '#f00' : '#fff'} />
+ <span>{post.likeCount}</span>
+ </button>
+ <Link href={`/forum/post/${post.id}`} className="icon-btn">
+ <Comment theme="outline" size="24" fill="#fff" />
+ <span>{post.commentCount}</span>
+ </Link>
+ </div>
+ <Link href={`/forum/post/${post.id}`} className="btn-secondary">查看详情</Link>
+ </div>
+ ))
+ }
+
+ <div className="pagination">
+ <button disabled={page === 1} onClick={() => setPage(page - 1)}>上一页</button>
+ <span>第 {page} 页 / 共 {totalPages} 页</span>
+ <button disabled={page === totalPages} onClick={() => setPage(page + 1)}>下一页</button>
+ </div>
+ </div>
+ );
+};
+
+export default PostList;
diff --git a/src/pages/Forum/posts-main/components/SearchBar.css b/src/pages/Forum/posts-main/components/SearchBar.css
new file mode 100644
index 0000000..b74f9d2
--- /dev/null
+++ b/src/pages/Forum/posts-main/components/SearchBar.css
@@ -0,0 +1,7 @@
+.search-bar {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ margin-bottom: 20px;
+ }
+
\ No newline at end of file
diff --git a/src/pages/Forum/posts-main/components/SearchBar.jsx b/src/pages/Forum/posts-main/components/SearchBar.jsx
new file mode 100644
index 0000000..52b873d
--- /dev/null
+++ b/src/pages/Forum/posts-main/components/SearchBar.jsx
@@ -0,0 +1,28 @@
+import React, { useState } from 'react';
+import './SearchBar.css';
+
+const SearchBar = ({ onSearch }) => {
+ const [query, setQuery] = useState('');
+
+ const handleSearch = () => onSearch(query);
+ const handleReset = () => {
+ setQuery('');
+ onSearch('');
+ };
+
+ return (
+ <div className="search-bar">
+ <input
+ type="text"
+ value={query}
+ onChange={e => setQuery(e.target.value)}
+ placeholder="标题"
+ className="search-input"
+ />
+ <button onClick={handleSearch} className="search-btn">搜索</button>
+ <button onClick={handleReset} className="search-btn">重置</button>
+ </div>
+ );
+};
+
+export default SearchBar;