fix: 修复评论用户名显示不一致问题(乐观更新显示正确,刷新后显示 Anonymous)

问题描述:
- 用户发表评论时,乐观更新显示用户名 "zdl"
- 但 API 返回后,用户名变成 "Anonymous"
- 刷新页面后,用户名仍然是 "Anonymous"

根本原因:
- 前端代码期望评论对象包含 `author` 字段(src/types/comment.ts)
- 后端 API 返回的是 `user` 字段(app.py:7710-7714)
- 前端渲染时读取 comment.author?.username(CommentItem.js:72)
- 因为 comment.author 不存在,所以显示 'Anonymous'

修复方案:
- 在 eventService.getPosts 中添加数据转换逻辑
- 将后端返回的 user 字段映射为前端期望的 author 字段
- 兼容 avatar_url 和 avatar 两种字段名
- 处理 user 为 null 的边界情况(显示 Anonymous)

影响范围:
- src/services/eventService.js - getPosts 函数数据转换
- 所有使用 getPosts API 的组件都会受益于此修复
- 保持类型定义不变,符合业务语义

修复效果:
- 乐观更新显示:zdl 刚刚 打卡
- API 返回后显示:zdl 刚刚 打卡 (之前会变成 Anonymous)
- 刷新页面后显示:zdl XX分钟前 打卡 

🤖 Generated with Claude Code
This commit is contained in:
zdl
2025-11-17 11:08:59 +08:00
parent 3a02c13dfe
commit 8d3327e4dd

View File

@@ -166,7 +166,27 @@ export const eventService = {
// 帖子相关API
getPosts: async (eventId, sortType = 'latest', page = 1, perPage = 20) => {
try {
return await apiRequest(`/api/events/${eventId}/posts?sort=${sortType}&page=${page}&per_page=${perPage}`);
const result = await apiRequest(`/api/events/${eventId}/posts?sort=${sortType}&page=${page}&per_page=${perPage}`);
// ⚡ 数据转换:将后端的 user 字段映射为前端期望的 author 字段
if (result.success && Array.isArray(result.data)) {
result.data = result.data.map(post => ({
...post,
author: post.user ? {
id: post.user.id,
username: post.user.username,
avatar: post.user.avatar_url || post.user.avatar // 兼容 avatar_url 和 avatar
} : {
id: 'anonymous',
username: 'Anonymous',
avatar: null
}
// 保留原始的 user 字段(如果其他地方需要)
// user: post.user
}));
}
return result;
} catch (error) {
logger.error('eventService', 'getPosts', error, { eventId, sortType, page });
return { success: false, data: [], pagination: {} };