fix(community): persist post liked status in MySQL and local storage to prevent state loss on page switch

这个提交包含在:
xcbyy
2026-10-13 15:46:04 +08:00
父节点 3d895a1a0a
当前提交 497fb65359
共有 6 个文件被更改,包括 218 次插入 和 40 次删除

查看文件

@@ -376,9 +376,14 @@ onUnmounted(() => {
const loadRemotePosts = async () => {
try {
const list = await getPosts();
const list = await getPosts(currentTab.value);
if (list && list.length > 0) {
posts.value = list;
let localLikedIds = uni.getStorageSync('COMMUNITY_LIKED_POST_IDS') || [];
if (!Array.isArray(localLikedIds)) localLikedIds = [];
posts.value = list.map(item => ({
...item,
liked: item.liked !== undefined ? item.liked : localLikedIds.includes(String(item.id))
}));
}
} catch (err) {
console.warn('[Community] 获取动态列表失败,保持本地列表:', err.message);
@@ -411,7 +416,20 @@ const feedTabs = ref([
const currentTab = ref('all');
const posts = ref([
const syncInitialLikedState = (rawPosts) => {
try {
let localLikedIds = uni.getStorageSync('COMMUNITY_LIKED_POST_IDS') || [];
if (!Array.isArray(localLikedIds) || localLikedIds.length === 0) return rawPosts;
return rawPosts.map(p => ({
...p,
liked: localLikedIds.includes(String(p.id)) ? true : p.liked
}));
} catch (_) {
return rawPosts;
}
};
const posts = ref(syncInitialLikedState([
{
id: 1,
author: '小甜橙',
@@ -476,7 +494,7 @@ const posts = ref([
views: 520,
category: 'partner'
}
]);
]));
const filteredPosts = computed(() => {
if (currentTab.value === 'all') return posts.value;
@@ -488,16 +506,43 @@ const switchFeedTab = (key) => {
};
const toggleLike = async (post) => {
post.liked = !post.liked;
post.likes += post.liked ? 1 : -1;
const willLike = !post.liked;
post.liked = willLike;
post.likes += willLike ? 1 : -1;
// 1. 同步更新本地存储的点赞记录 (保障切页、断网或刷新时不丢失状态)
let localLikedIds = uni.getStorageSync('COMMUNITY_LIKED_POST_IDS') || [];
if (!Array.isArray(localLikedIds)) localLikedIds = [];
const strId = String(post.id);
if (willLike) {
if (!localLikedIds.includes(strId)) localLikedIds.push(strId);
} else {
localLikedIds = localLikedIds.filter(id => id !== strId);
}
uni.setStorageSync('COMMUNITY_LIKED_POST_IDS', localLikedIds);
uni.showToast({
title: post.liked ? '已点赞' : '已取消点赞',
title: willLike ? '已点赞' : '已取消点赞',
icon: 'none',
duration: 1000
});
if (post.liked && post.id) {
if (post.id) {
try {
await likePost(post.id);
const res = await likePost(post.id, willLike ? 'like' : 'unlike');
if (res && res.likes !== undefined) {
post.likes = res.likes;
}
if (res && res.liked !== undefined) {
post.liked = res.liked;
if (res.liked && !localLikedIds.includes(strId)) {
localLikedIds.push(strId);
uni.setStorageSync('COMMUNITY_LIKED_POST_IDS', localLikedIds);
} else if (!res.liked && localLikedIds.includes(strId)) {
localLikedIds = localLikedIds.filter(id => id !== strId);
uni.setStorageSync('COMMUNITY_LIKED_POST_IDS', localLikedIds);
}
}
} catch (err) {
console.warn('[Community] 点赞落盘异常:', err.message);
}