为多个组件和API添加用户登录状态检查,确保只有在用户登录后才能查询和修改收藏状态

This commit is contained in:
yuchenglong
2026-01-16 18:02:08 +08:00
parent b5fd763c7e
commit 887d205f65
8 changed files with 107 additions and 50 deletions

View File

@@ -13,6 +13,7 @@ import {
fetchSports,
fetchUpcomingMatches,
} from "@/lib/api";
import { storage } from "@/lib/storage";
import { League, Sport, UpcomingMatch } from "@/types/api";
import React, { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
@@ -261,7 +262,8 @@ export default function HomeScreen() {
};
const loadMatches = async () => {
if (selectedSportId === null) return;
const token = await storage.getAccessToken();
if (selectedSportId === null || !token) return;
setLoading(true);
try {
@@ -271,18 +273,23 @@ export default function HomeScreen() {
selectedLeagueKey || ""
);
// 直接传递 match.id 查询是否收藏,并更新列表状态
const listWithFavStatus = await Promise.all(
list.map(async (m) => {
try {
const favRes = await checkFavorite("match", m.id.toString());
return { ...m, fav: favRes.isFavorite };
} catch (error) {
console.error(`Check favorite failed for match ${m.id}:`, error);
return m;
}
})
);
const token = await storage.getAccessToken();
let listWithFavStatus = list;
if (token) {
// 直接传递 match.id 查询是否收藏,并更新列表状态
listWithFavStatus = await Promise.all(
list.map(async (m) => {
try {
const favRes = await checkFavorite("match", m.id.toString());
return { ...m, fav: favRes.isFavorite };
} catch (error) {
console.error(`Check favorite failed for match ${m.id}:`, error);
return m;
}
})
);
}
// 将收藏的比赛置顶
const sortedList = [...listWithFavStatus].sort((a, b) => {