修改论坛、促销、登录,增加测试
Change-Id: I71883fc1da46a94db47f90a4cd61474c274a5b2c
diff --git a/src/pages/Forum/posts-create/CreatePost.jsx b/src/pages/Forum/posts-create/CreatePost.jsx
index e38c29a..b8e8c2a 100644
--- a/src/pages/Forum/posts-create/CreatePost.jsx
+++ b/src/pages/Forum/posts-create/CreatePost.jsx
@@ -1,89 +1,78 @@
-// // src/pages/Forum/CreatePost.jsx
// import React, { useState } from 'react';
// import axios from 'axios';
+// import './CreatePost.css'; // 如果你打算加样式
// const API_BASE = process.env.REACT_APP_API_BASE;
-// const CreatePost = ({ userId }) => {
+// const CreatePost = ({ user_id }) => {
// const [title, setTitle] = useState('');
// const [content, setContent] = useState('');
-// const [imgUrl, setImageUrl] = useState('');
-// const [isAnonymous, setIsAnonymous] = useState(false);
+// const [imageUrl, setImageUrl] = useState('');
+// const [message, setMessage] = useState('');
+// const [error, setError] = useState('');
// const handleSubmit = async (e) => {
// e.preventDefault();
+// setMessage('');
+// setError('');
+
+// if (!title.trim() || !content.trim()) {
+// setError('标题和内容不能为空');
+// return;
+// }
// try {
-// const postData = {
+// const res = await axios.post(`${API_BASE}/echo/forum/posts/${user_id}/createPost`, {
// title,
-// postContent: content,
-// postType: isAnonymous,
-// };
+// post_content: content,
+// image_url: imageUrl
+// });
-// if (imgUrl.trim()) {
-// postData.imgUrl = imgUrl;
-// }
-
-// const response = await axios.post(
-// `${API_BASE}/echo/forum/posts/${userId}/createPost`,
-// postData
-// );
-
-
-// if (response.status === 201) {
-// alert('帖子创建成功!');
-// setTitle('');
-// setContent('');
-// setImageUrl('');
-// setIsAnonymous(false);
-// }
-// } catch (error) {
-// console.error('帖子创建失败:', error.response?.data || error.message);
-// alert('创建失败,请重试');
-// }
+// setMessage(`发帖成功,帖子ID:${res.data.post_id}`);
+// setTitle('');
+// setContent('');
+// setImageUrl('');
+// } catch (err) {
+// console.error(err);
+// setError(err.response?.data?.error || '发帖失败,请稍后重试');
+// }
// };
// return (
-// <div className="create-post">
-// <h2>创建新帖子</h2>
-// <form onSubmit={handleSubmit}>
-// <div>
+// <div className="create-post-container">
+// <h2>发表新帖子</h2>
+// <form onSubmit={handleSubmit} className="create-post-form">
+// <div className="form-group">
// <label>标题:</label>
// <input
// type="text"
// value={title}
// onChange={(e) => setTitle(e.target.value)}
-// required
+// placeholder="输入帖子标题"
// />
// </div>
-// <div>
+// <div className="form-group">
// <label>内容:</label>
// <textarea
// value={content}
// onChange={(e) => setContent(e.target.value)}
-// required
+// placeholder="输入帖子内容"
// />
// </div>
-// <div>
-// <label>图片 URL(可选):</label>
+// <div className="form-group">
+// <label>图片链接(可选):</label>
// <input
// type="text"
-// value={imgUrl}
+// value={imageUrl}
// onChange={(e) => setImageUrl(e.target.value)}
+// placeholder="例如:https://example.com/img.jpg"
// />
// </div>
-// <div>
-// <label>
-// <input
-// type="checkbox"
-// checked={isAnonymous}
-// onChange={(e) => setIsAnonymous(e.target.checked)}
-// />
-// 匿名发布
-// </label>
-// </div>
// <button type="submit">发布</button>
// </form>
+
+// {message && <p className="success-text">{message}</p>}
+// {error && <p className="error-text">{error}</p>}
// </div>
// );
// };
@@ -96,7 +85,7 @@
const API_BASE = process.env.REACT_APP_API_BASE;
-const CreatePost = ({ userId }) => {
+const CreatePost = ({ user_id }) => {
const [title, setTitle] = useState('');
const [content, setContent] = useState('');
const [imageUrl, setImageUrl] = useState('');
@@ -114,7 +103,7 @@
}
try {
- const res = await axios.post(`${API_BASE}/echo/forum/posts/${userId}/createPost`, {
+ const res = await axios.post(`${API_BASE}/echo/forum/posts/${user_id}/createPost`, {
title,
post_content: content,
image_url: imageUrl
@@ -135,8 +124,10 @@
<h2>发表新帖子</h2>
<form onSubmit={handleSubmit} className="create-post-form">
<div className="form-group">
- <label>标题:</label>
+ {/* 这里加上htmlFor,并给input加id */}
+ <label htmlFor="title">标题:</label>
<input
+ id="title" // 加id
type="text"
value={title}
onChange={(e) => setTitle(e.target.value)}
@@ -144,16 +135,20 @@
/>
</div>
<div className="form-group">
- <label>内容:</label>
+ {/* 同理,内容 */}
+ <label htmlFor="content">内容:</label>
<textarea
+ id="content" // 加id
value={content}
onChange={(e) => setContent(e.target.value)}
placeholder="输入帖子内容"
/>
</div>
<div className="form-group">
- <label>图片链接(可选):</label>
+ {/* 图片链接 */}
+ <label htmlFor="imageUrl">图片链接(可选):</label>
<input
+ id="imageUrl" // 加id
type="text"
value={imageUrl}
onChange={(e) => setImageUrl(e.target.value)}
diff --git a/src/pages/Forum/posts-detail/PostDetailPage.css b/src/pages/Forum/posts-detail/PostDetailPage.css
index 780492b..570b65f 100644
--- a/src/pages/Forum/posts-detail/PostDetailPage.css
+++ b/src/pages/Forum/posts-detail/PostDetailPage.css
@@ -1,5 +1,5 @@
.post-detail-page {
- background: linear-gradient(180deg, #5F4437, #823c3c);
+ background: #333;
font-family: 'Helvetica Neue', sans-serif;
color: #333;
}
diff --git a/src/pages/Forum/posts-detail/PostDetailPage.jsx b/src/pages/Forum/posts-detail/PostDetailPage.jsx
index 01e1648..c58ed33 100644
--- a/src/pages/Forum/posts-detail/PostDetailPage.jsx
+++ b/src/pages/Forum/posts-detail/PostDetailPage.jsx
@@ -1,7 +1,288 @@
+// import React, { useEffect, useState } from 'react';
+// import { useParams } from 'wouter';
+// import { GoodTwo, Star } from '@icon-park/react';
+// import { getPostDetail, getPostComments, likePost, unlikePost, addCommentToPost, collectPost } from './api'; // 引入你的 API 函数
+// import './PostDetailPage.css';
+// import { useUser } from '../../../context/UserContext'; // 注意路径
+// import Header from '../../../components/Header';
+
+// const PostDetailPage = () => {
+// const { postId } = useParams(); // 获取帖子ID
+// const [postDetail, setPostDetail] = useState(null);
+// const [comments, setComments] = useState([]);
+// const [loading, setLoading] = useState(true);
+// const [errorMsg, setErrorMsg] = useState('');
+// const [newComment, setNewComment] = useState(''); // 新评论内容
+// const [isAnonymous, setIsAnonymous] = useState(false); // 是否匿名
+// const [isLiked, setIsLiked] = useState(false); // 是否已点赞
+// const [isCollected, setIsCollected] = useState(false); // 是否已收藏
+// const [replyToCommentId, setReplyToCommentId] = useState(null); // 回复的评论ID
+
+// // 获取当前用户ID(假设从上下文中获取)
+// const { user } = useUser(); // 你需要从用户上下文获取用户 ID
+
+// useEffect(() => {
+// const fetchPostDetail = async () => {
+// setLoading(true);
+// setErrorMsg('');
+// try {
+// // 获取帖子详情
+// const postData = await getPostDetail(postId);
+// setPostDetail(postData);
+
+// // 获取帖子评论
+// const commentsData = await getPostComments(postId);
+// setComments(commentsData);
+
+// // 设置是否已经点赞
+// if (postData.likedByUser) {
+// setIsLiked(true);
+// } else {
+// setIsLiked(false);
+// }
+
+// // 设置是否已经收藏
+// if (postData.collectedByUser) {
+// setIsCollected(true);
+// } else {
+// setIsCollected(false);
+// }
+// } catch (err) {
+// console.error('加载失败:', err);
+// setErrorMsg('加载失败,请稍后重试');
+// } finally {
+// setLoading(false);
+// }
+// };
+
+// fetchPostDetail();
+// }, [postId]);
+
+// // 点赞功能
+// const toggleLike = async () => {
+// if (!user) {
+// alert('请先登录');
+// return;
+// }
+
+// try {
+// if (isLiked) {
+// // 取消点赞
+// await unlikePost(postId, user.id);
+// setIsLiked(false);
+// setPostDetail((prev) => ({
+// ...prev,
+// postLikeNum: prev.postLikeNum - 1,
+// }));
+// } else {
+// // 点赞
+// await likePost(postId, user.id);
+// setIsLiked(true);
+// setPostDetail((prev) => ({
+// ...prev,
+// postLikeNum: prev.postLikeNum + 1,
+// }));
+// }
+// } catch (err) {
+// console.error('点赞失败:', err);
+// alert('点赞失败,请稍后再试');
+// }
+// };
+
+// // 收藏功能
+// const toggleCollect = async () => {
+// if (!user) {
+// alert('请先登录');
+// return;
+// }
+
+// try {
+// const action = isCollected ? 'cancel' : 'collect';
+// // 调用收藏 API
+// await collectPost(postId, user.id, action);
+// setIsCollected(!isCollected);
+// setPostDetail((prev) => ({
+// ...prev,
+// postCollectNum: isCollected ? prev.postCollectNum - 1 : prev.postCollectNum + 1,
+// }));
+// } catch (err) {
+// console.error('收藏失败:', err);
+// alert('收藏失败,请稍后再试');
+// }
+// };
+
+// // 添加评论
+// const handleAddComment = async () => {
+// if (!newComment.trim()) {
+// alert('评论内容不能为空');
+// return;
+// }
+
+// try {
+// // 调用 API 添加评论,若为回复评论则传递父评论ID(com_comment_id)
+// const commentData = await addCommentToPost(postId, user.id, newComment, isAnonymous, replyToCommentId);
+// // 更新评论列表
+// setComments((prev) => [
+// ...prev,
+// {
+// commentId: commentData.commentId,
+// post_id: postId,
+// userId: user.id,
+// content: newComment,
+// isAnonymous,
+// commentTime: new Date().toISOString(),
+// comCommentId: replyToCommentId, // 回复评论时传递父评论ID
+// },
+// ]);
+// // 清空评论框和回复状态
+// setNewComment('');
+// setReplyToCommentId(null);
+// } catch (err) {
+// console.error('评论添加失败:', err);
+// alert('评论失败,请稍后再试');
+// }
+// };
+
+// // 回复评论
+// const handleReply = (commentId) => {
+// setReplyToCommentId(commentId); // 设置父评论ID为当前评论的ID
+// };
+
+// return (
+// <div className="post-detail-page">
+// <Header />
+// {loading ? (
+// <p>加载中...</p>
+// ) : errorMsg ? (
+// <p className="error-text">{errorMsg}</p>
+// ) : postDetail ? (
+// <div className="post-detail">
+// <h1>{postDetail.title}</h1>
+// <div className="post-meta">
+// <span className="post-user">用户ID: {postDetail.user_id}</span>
+// <span className="post-time">
+// 发布时间:{new Date(postDetail.postTime).toLocaleString()}
+// </span>
+// </div>
+// <div className="post-content">
+// <p>{postDetail.postContent}</p>
+// {Array.isArray(postDetail.imgUrl) ? (
+// <div className="post-images">
+// {postDetail.imgUrl.map((url, idx) => (
+// <img key={idx} src={url} alt={`图片${idx}`} />
+// ))}
+// </div>
+// ) : (
+// postDetail.imgUrl && (
+// <img className="post-image" src={postDetail.imgUrl} alt="帖子图片" />
+// )
+// )}
+
+// </div>
+
+// {/* 点赞和收藏 */}
+// <div className="post-actions">
+// <button
+// className="icon-btn"
+// onClick={toggleLike} // 点赞操作
+// >
+// <GoodTwo
+// theme="outline"
+// size="20"
+// fill={isLiked ? '#f00' : '#ccc'} // 如果已点赞,显示红色
+// />
+// <span>{postDetail.postLikeNum}</span>
+// </button>
+// <button
+// className="icon-btn"
+// onClick={toggleCollect} // 收藏操作
+// >
+// <Star
+// theme="outline"
+// size="20"
+// fill={isCollected ? '#ffd700' : '#ccc'} // 如果已收藏,显示金色
+// />
+// <span>{postDetail.postCollectNum}</span>
+// </button>
+// </div>
+
+// <hr className="divider" />
+// {/* 评论部分 */}
+// <h3>评论区</h3>
+// <div className="comments-section">
+// {comments.length ? (
+// comments.map((comment) => (
+// <div key={comment.commentId} className="comment">
+// <div className="comment-header">
+// <span className="comment-user">用户 ID: {comment.userId}</span>
+// <button className="reply-btn" onClick={() => handleReply(comment.commentId)}>回复</button>
+// </div>
+// <p className="comment-content">{comment.content}</p>
+// <div className="comment-time">
+// {new Date(comment.commentTime).toLocaleString()}
+// </div>
+
+// {/* 回复框,只有在当前评论是正在回复的评论时显示 */}
+// {replyToCommentId === comment.commentId && (
+// <div className="reply-form">
+// <textarea
+// placeholder="输入你的回复..."
+// value={newComment}
+// onChange={(e) => setNewComment(e.target.value)}
+// />
+// <div className="comment-options">
+// <label>
+// <input
+// type="checkbox"
+// checked={isAnonymous}
+// onChange={() => setIsAnonymous(!isAnonymous)}
+// />
+// 匿名评论
+// </label>
+// <button onClick={handleAddComment}>发布回复</button>
+// </div>
+// </div>
+// )}
+// </div>
+// ))
+// ) : (
+// <p>暂无评论</p>
+// )}
+
+// {/* 添加评论表单 */}
+// <div className="add-comment-form">
+// <textarea
+// placeholder="输入你的评论..."
+// value={newComment}
+// onChange={(e) => setNewComment(e.target.value)}
+// />
+// <div className="comment-options">
+// <label>
+// <input
+// type="checkbox"
+// checked={isAnonymous}
+// onChange={() => setIsAnonymous(!isAnonymous)}
+// />
+// 匿名评论
+// </label>
+// <button onClick={handleAddComment}>发布评论</button>
+// </div>
+// </div>
+// </div>
+// </div>
+// ) : (
+// <p>帖子不存在</p>
+// )}
+// </div>
+// );
+// };
+
+// export default PostDetailPage;
+
import React, { useEffect, useState } from 'react';
import { useParams } from 'wouter';
import { GoodTwo, Star } from '@icon-park/react';
-import { getPostDetail, getPostComments, likePost, unlikePost, addCommentToPost, collectPost } from './api'; // 引入你的 API 函数
+import { getPostDetail, getPostComments, likePost, unlikePost, addCommentToPost, collectPost, uncollectPost } from './api'; // 引入你的 API 函数
import './PostDetailPage.css';
import { useUser } from '../../../context/UserContext'; // 注意路径
import Header from '../../../components/Header';
@@ -13,7 +294,7 @@
const [loading, setLoading] = useState(true);
const [errorMsg, setErrorMsg] = useState('');
const [newComment, setNewComment] = useState(''); // 新评论内容
- const [isAnonymous, setIsAnonymous] = useState(false); // 是否匿名
+ // const [isAnonymous, setIsAnonymous] = useState(false); // 是否匿名
const [isLiked, setIsLiked] = useState(false); // 是否已点赞
const [isCollected, setIsCollected] = useState(false); // 是否已收藏
const [replyToCommentId, setReplyToCommentId] = useState(null); // 回复的评论ID
@@ -89,27 +370,36 @@
}
};
- // 收藏功能
- const toggleCollect = async () => {
+// 收藏功能
+const toggleCollect = async () => {
if (!user) {
- alert('请先登录');
- return;
+ alert('请先登录');
+ return;
}
try {
- const action = isCollected ? 'cancel' : 'collect';
- // 调用收藏 API
- await collectPost(postId, user.id, action);
- setIsCollected(!isCollected);
- setPostDetail((prev) => ({
- ...prev,
- postCollectNum: isCollected ? prev.postCollectNum - 1 : prev.postCollectNum + 1,
- }));
+ if (isCollected) {
+ // 取消收藏 - 使用原有的collectPost函数,传递action: "cancel"
+ await collectPost(postId, user.id, "cancel");
+ setIsCollected(false);
+ setPostDetail((prev) => ({
+ ...prev,
+ postCollectNum: prev.postCollectNum - 1,
+ }));
+ } else {
+ // 收藏
+ await collectPost(postId, user.id, "collect");
+ setIsCollected(true);
+ setPostDetail((prev) => ({
+ ...prev,
+ postCollectNum: prev.postCollectNum + 1,
+ }));
+ }
} catch (err) {
- console.error('收藏失败:', err);
- alert('收藏失败,请稍后再试');
+ console.error('收藏操作失败:', err);
+ alert('收藏操作失败,请稍后再试');
}
- };
+};
// 添加评论
const handleAddComment = async () => {
@@ -120,7 +410,7 @@
try {
// 调用 API 添加评论,若为回复评论则传递父评论ID(com_comment_id)
- const commentData = await addCommentToPost(postId, user.id, newComment, isAnonymous, replyToCommentId);
+ const commentData = await addCommentToPost(postId, user.id, newComment, replyToCommentId);
// 更新评论列表
setComments((prev) => [
...prev,
@@ -129,7 +419,7 @@
post_id: postId,
userId: user.id,
content: newComment,
- isAnonymous,
+ // isAnonymous,
commentTime: new Date().toISOString(),
comCommentId: replyToCommentId, // 回复评论时传递父评论ID
},
@@ -231,14 +521,14 @@
onChange={(e) => setNewComment(e.target.value)}
/>
<div className="comment-options">
- <label>
- <input
- type="checkbox"
- checked={isAnonymous}
- onChange={() => setIsAnonymous(!isAnonymous)}
- />
- 匿名评论
- </label>
+ {/* <label> */}
+ {/* <input */}
+ {/* type="checkbox" */}
+ {/* checked={isAnonymous} */}
+ {/* onChange={() => setIsAnonymous(!isAnonymous)} */}
+ {/* /> */}
+ {/* 匿名评论 */}
+ {/* </label> */}
<button onClick={handleAddComment}>发布回复</button>
</div>
</div>
@@ -257,14 +547,14 @@
onChange={(e) => setNewComment(e.target.value)}
/>
<div className="comment-options">
- <label>
+ {/* <label>
<input
type="checkbox"
checked={isAnonymous}
onChange={() => setIsAnonymous(!isAnonymous)}
/>
匿名评论
- </label>
+ </label> */}
<button onClick={handleAddComment}>发布评论</button>
</div>
</div>
@@ -277,4 +567,4 @@
);
};
-export default PostDetailPage;
+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
index d05f148..27c3a18 100644
--- a/src/pages/Forum/posts-detail/api.js
+++ b/src/pages/Forum/posts-detail/api.js
@@ -2,22 +2,23 @@
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`);
+export const getPostDetail = async (post_id) => {
+ const response = await axios.get(`${API_BASE}/echo/forum/posts/${post_id}/getPost`);
return response.data;
};
// 获取帖子评论
-export const getPostComments = async (postId) => {
- const response = await axios.get(`${API_BASE}/echo/forum/posts/${postId}/getAllComments`);
+export const getPostComments = async (post_id) => {
+ const response = await axios.get(`${API_BASE}/echo/forum/posts/${post_id}/getAllComments`);
return response.data;
};
// 点赞帖子
-export const likePost = async (postId, userId) => {
+export const likePost = async (post_id, userId) => {
try {
- const response = await axios.post(`${API_BASE}/echo/forum/posts/${postId}/like`, {
+ const response = await axios.post(`${API_BASE}/echo/forum/posts/${post_id}/like`, {
user_id: userId, // 用户 ID
});
return response.data;
@@ -27,15 +28,15 @@
};
// 取消点赞帖子
-export const unlikePost = async (postId) => {
- const response = await axios.delete(`${API_BASE}/echo/forum/posts/${postId}/unlike`);
+export const unlikePost = async (post_id) => {
+ const response = await axios.delete(`${API_BASE}/echo/forum/posts/${post_id}/unlike`);
return response.data;
};
// 添加评论
-export const addCommentToPost = async (postId, userId, content, isAnonymous, comCommentId = null) => {
+export const addCommentToPost = async (post_id, userId, content, isAnonymous, comCommentId = null) => {
try {
- const response = await axios.post(`${API_BASE}/echo/forum/posts/${postId}/comments`, {
+ const response = await axios.post(`${API_BASE}/echo/forum/posts/${post_id}/comments`, {
content,
user_id: userId,
is_anonymous: isAnonymous,
@@ -60,9 +61,9 @@
};
// 收藏帖子
-export const collectPost = async (postId, userId, action) => {
+export const collectPost = async (post_id, userId, action) => {
try {
- const response = await axios.post(`${API_BASE}/echo/forum/posts/${postId}/collect`, {
+ const response = await axios.post(`${API_BASE}/echo/forum/posts/${post_id}/collect`, {
user_id: userId,
action: action, // "collect" 或 "cancel"
});
@@ -72,6 +73,14 @@
}
};
+// // 取消收藏帖子
+// export const uncollectPost = async (post_id, userId) => {
+// const response = await axios.post(`${API_BASE}/echo/forum/posts/${post_id}/uncollect`, {
+// user_id: userId, // 用户 ID
+// });
+// return response.data;
+// };
+
// 获取用户信息
export const getUserInfo = async (userId) => {
const response = await axios.get(`${API_BASE}/user/${userId}/info`);
diff --git a/src/pages/Forum/posts-main/ForumPage.css b/src/pages/Forum/posts-main/ForumPage.css
index 8a7ae4c..5fd64a2 100644
--- a/src/pages/Forum/posts-main/ForumPage.css
+++ b/src/pages/Forum/posts-main/ForumPage.css
@@ -2,7 +2,7 @@
color: #fff;
/* background-color: #5F4437; */
/* background: linear-gradient(180deg, #5F4437, #9c737b); */
- background: linear-gradient(180deg, #5F4437, #823c3c);
+ background: #333;
/* background-color: #5F4437; */
min-height: 100vh;
font-family: Arial, sans-serif;
diff --git a/src/pages/Forum/posts-main/components/CreatePostButton.jsx b/src/pages/Forum/posts-main/components/CreatePostButton.jsx
index 0390ee7..4f7d7b1 100644
--- a/src/pages/Forum/posts-main/components/CreatePostButton.jsx
+++ b/src/pages/Forum/posts-main/components/CreatePostButton.jsx
@@ -4,7 +4,7 @@
import './CreatePostButton.css';
const API_BASE = process.env.REACT_APP_API_BASE;
-const USER_ID = 456;
+const user_id = 456;
const CreatePostButton = () => {
const [showModal, setShowModal] = useState(false);
@@ -49,7 +49,7 @@
try {
await axios.post(
- `${API_BASE}/echo/forum/posts/${USER_ID}/createPost`,
+ `${API_BASE}/echo/forum/posts/${user_id}/createPost`,
{
title: title.trim(),
post_content: content.trim(),
diff --git a/src/pages/Forum/posts-main/components/PostList.jsx b/src/pages/Forum/posts-main/components/PostList.jsx
index 3eba6f8..707ff15 100644
--- a/src/pages/Forum/posts-main/components/PostList.jsx
+++ b/src/pages/Forum/posts-main/components/PostList.jsx
@@ -1,175 +1,8 @@
-// import React, { useEffect, useState } from 'react';
-// import axios from 'axios';
-// import { Link } from 'wouter';
-// import { GoodTwo, Comment, Star } from '@icon-park/react';
-// import { likePost, unlikePost, collectPost } from '../../posts-detail/api';
-// 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`, {
-// params: {
-// page: page,
-// pageSize: size,
-// sortBy: 'createdAt', // 按时间排序
-// order: 'desc' // 按降序排序
-// }
-// });
-
-// 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, userId) => {
-// try {
-// if (liked) {
-// await unlikePost(postId); // 取消点赞
-// } else {
-// await likePost(postId, userId); // 点赞
-// }
-
-// 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);
-// }
-// };
-
-// // 收藏/取消收藏操作
-// const toggleCollect = async (postId, collected, userId) => {
-// try {
-// const action = collected ? 'cancel' : 'collect';
-// await collectPost(postId, userId, action);
-
-// setPosts(posts =>
-// posts.map(post =>
-// post.id === postId
-// ? { ...post, collected: !collected, collectCount: collected ? post.collectCount - 1 : post.collectCount + 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 => (
-// <Link
-// key={post.id}
-// href={`/forum/post/${post.id}`}
-// className="post-card"
-// style={{ backgroundColor: '#e9ded2' }}
-// >
-// <div className="user-info">
-// <img className="avatar" src={post.userProfile.avatar_url} alt="头像" />
-// <span className="nickname" style={{ color: '#755e50' }}>{post.userProfile.nickname}</span>
-// </div>
-// {post.cover_image_url && (
-// <img className="cover-image" src={post.cover_image_url} alt="封面" />
-// )}
-// <h3 style={{ color: '#000000' }}>{post.title}</h3>
-// <div className="post-meta">
-// <span>发布时间:{new Date(post.createdAt).toLocaleString()}</span>
-// <div className="post-actions">
-// {/* 点赞按钮 */}
-// <button className="icon-btn" onClick={(e) => { e.stopPropagation(); toggleLike(post.id, post.liked, post.user_id); }}>
-// <GoodTwo theme="outline" size="24" fill={post.liked ? '#f00' : '#fff'} />
-// <span>{post.likeCount}</span>
-// </button>
-
-// {/* 收藏按钮 */}
-// <button className="icon-btn" onClick={(e) => { e.stopPropagation(); toggleCollect(post.id, post.collected, post.user_id); }}>
-// <Star theme="outline" size="24" fill={post.collected ? '#ffd700' : '#fff'} />
-// <span>{post.collectCount}</span>
-// </button>
-
-// <Link href={`/forum/post/${post.id}`} className="icon-btn" onClick={(e) => e.stopPropagation()}>
-// <Comment theme="outline" size="24" fill="#fff" />
-// <span>{post.commentCount}</span>
-// </Link>
-// </div>
-// </div>
-// </Link>
-// ))
-// }
-
-// <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;
-
import React, { useEffect, useState } from 'react';
import axios from 'axios';
import { Link } from 'wouter';
-import { GoodTwo, Comment, Star } from '@icon-park/react';
-import { likePost, unlikePost, collectPost } from '../../posts-detail/api';
+import { GoodTwo, Comment, Star, Delete } from '@icon-park/react';
+import { likePost, unlikePost } from '../../posts-detail/api';
import './PostList.css';
const API_BASE = process.env.REACT_APP_API_BASE;
@@ -200,10 +33,8 @@
const postsData = res.data.posts || [];
- // 收集所有 user_id
const userIds = [...new Set(postsData.map(post => post.user_id))];
- // 批量请求用户资料
const profiles = await Promise.all(userIds.map(async id => {
try {
const r = await axios.get(`${API_BASE}/echo/user/profile`, {
@@ -215,13 +46,11 @@
}
}));
- // 创建 user_id -> profile 映射
const userMap = {};
profiles.forEach(({ id, profile }) => {
userMap[id] = profile;
});
- // 过滤并补充 profile
const postsWithProfiles = postsData
.filter(post => post.title.toLowerCase().includes(search.toLowerCase()))
.map(post => ({
@@ -265,10 +94,20 @@
}
};
+ // 收藏帖子
const toggleCollect = async (postId, collected, userId) => {
try {
- const action = collected ? 'cancel' : 'collect';
- await collectPost(postId, userId, action);
+ if (collected) {
+ // 取消收藏
+ await axios.get(`${API_BASE}/echo/forum/posts/${postId}/uncollect`, {
+ data: { user_id: userId }
+ });
+ } else {
+ // 收藏帖子
+ await axios.post(`${API_BASE}/echo/forum/posts/${postId}/collect`, {
+ user_id: userId
+ });
+ }
setPosts(posts =>
posts.map(post =>
@@ -278,7 +117,27 @@
)
);
} catch (err) {
- console.error('收藏失败:', err);
+ console.error('收藏操作失败:', err);
+ }
+ };
+
+ // 删除帖子
+ const handleDeletePost = async (postId) => {
+ if (window.confirm('确定要删除这篇帖子吗?')) {
+ try {
+ await axios.delete(`${API_BASE}/echo/forum/posts/${postId}/deletePost`);
+
+ // 从列表中移除已删除的帖子
+ setPosts(posts => posts.filter(post => post.postNo !== postId));
+
+ // 如果删除后当前页没有帖子了,尝试加载上一页
+ if (posts.length === 1 && page > 1) {
+ setPage(page - 1);
+ }
+ } catch (err) {
+ console.error('删除帖子失败:', err);
+ alert('删除帖子失败,请稍后再试');
+ }
}
};
@@ -288,9 +147,8 @@
errorMsg ? <p className="error-text">{errorMsg}</p> :
posts.length === 0 ? <p>暂无帖子。</p> :
posts.map(post => (
- <Link
+ <div
key={post.postNo}
- href={`/forum/post/${post.postNo}`}
className="post-card"
style={{ backgroundColor: '#e9ded2' }}
>
@@ -305,23 +163,30 @@
<div className="post-meta">
<span>发布时间:{new Date(post.createdAt).toLocaleString()}</span>
<div className="post-actions">
- <button className="icon-btn" onClick={(e) => { e.stopPropagation(); toggleLike(post.postNo, post.liked, post.user_id); }}>
+ <button className="icon-btn" onClick={() => toggleLike(post.postNo, post.liked, post.user_id)}>
<GoodTwo theme="outline" size="24" fill={post.liked ? '#f00' : '#fff'} />
<span>{post.likeCount}</span>
</button>
- <button className="icon-btn" onClick={(e) => { e.stopPropagation(); toggleCollect(post.postNo, post.collected, post.user_id); }}>
+ <button className="icon-btn" onClick={() => toggleCollect(post.postNo, post.collected, post.user_id)}>
<Star theme="outline" size="24" fill={post.collected ? '#ffd700' : '#fff'} />
<span>{post.collectCount}</span>
</button>
- <Link href={`/forum/post/${post.postNo}`} className="icon-btn" onClick={(e) => e.stopPropagation()}>
+ <div className="icon-btn">
<Comment theme="outline" size="24" fill="#fff" />
<span>{post.commentCount}</span>
- </Link>
+ </div>
+
+ <button className="icon-btn" onClick={() => handleDeletePost(post.postNo)}>
+ <Delete theme="outline" size="24" fill="#333" />
+ </button>
</div>
</div>
- </Link>
+ <div className="detail-button-wrapper">
+ <Link href={`/forum/post/${post.postNo}`} className="detail-button">查看详情</Link>
+ </div>
+ </div>
))
}
@@ -334,4 +199,4 @@
);
};
-export default PostList;
+export default PostList;
\ No newline at end of file