评论正常显示用户名称和头像
Change-Id: I801dbc85ed3bbefe1df600a404133d309ca563cc
diff --git a/Merge/front/src/components/PostDetailJWLLL.jsx b/Merge/front/src/components/PostDetailJWLLL.jsx
index 2745d79..d598a72 100644
--- a/Merge/front/src/components/PostDetailJWLLL.jsx
+++ b/Merge/front/src/components/PostDetailJWLLL.jsx
@@ -23,6 +23,8 @@
const [isFollowing, setIsFollowing] = useState(false)
const [authorInfo, setAuthorInfo] = useState(null)
const [previewImg, setPreviewImg] = useState(null)
+ const [commentUserMap, setCommentUserMap] = useState({}) // user_id: username
+ const [commentUserAvatarMap, setCommentUserAvatarMap] = useState({}) // user_id: avatar
// 获取当前用户ID
const getCurrentUserId = () => {
const userInfo = getUserInfo()
@@ -80,11 +82,48 @@
}
}, [post])
+ // 拉取所有评论用户昵称
+ const fetchCommentUserNames = async (userIds) => {
+ const map = {}
+ await Promise.all(userIds.map(async uid => {
+ try {
+ const user = await postsAPI.getUser(uid)
+ map[uid] = user.username || user.nickname || `用户${uid}`
+ } catch {
+ map[uid] = `用户${uid}`
+ }
+ }))
+ setCommentUserMap(map)
+ }
+
+ // 拉取所有评论用户头像
+ const fetchCommentUserAvatars = async (userIds) => {
+ const map = {}
+ await Promise.all(userIds.map(async uid => {
+ try {
+ const user = await postsAPI.getUser(uid)
+ map[uid] = user.avatar && user.avatar.startsWith('http') ? user.avatar : (user.avatar ? `http://10.126.59.25:5715/static/${user.avatar}` : `https://i.pravatar.cc/40?img=${uid}`)
+ } catch {
+ map[uid] = `https://i.pravatar.cc/40?img=${uid}`
+ }
+ }))
+ setCommentUserAvatarMap(map)
+ }
+
useEffect(() => {
fetchPostDetail()
fetchComments()
}, [fetchPostDetail, fetchComments])
+ // 评论区用户昵称和头像拉取
+ useEffect(() => {
+ if (comments.length > 0) {
+ const userIds = [...new Set(comments.map(c => c.user_id).filter(Boolean))]
+ fetchCommentUserNames(userIds)
+ fetchCommentUserAvatars(userIds)
+ }
+ }, [comments])
+
const handleBack = () => {
navigate(-1)
}
@@ -350,9 +389,9 @@
<div key={index} className="comment-item">
<div className="comment-author">
<div className="comment-avatar">
- {comment.user_name ? comment.user_name.charAt(0).toUpperCase() : 'U'}
+ <img className="avatar" src={commentUserAvatarMap[comment.user_id] || `https://i.pravatar.cc/40?img=${comment.user_id}`} alt={commentUserMap[comment.user_id] || comment.user_name || '用户'} />
</div>
- <span className="comment-name">{comment.user_name || '匿名用户'}</span>
+ <span className="comment-name">{commentUserMap[comment.user_id] || comment.user_name || '匿名用户'}</span>
<span className="comment-time">
{comment.create_time ? new Date(comment.create_time).toLocaleString('zh-CN') : ''}
</span>