This commit is contained in:
xianyi
2026-01-19 17:42:42 +08:00
parent e1320a67e4
commit ee66f383b1
3 changed files with 115 additions and 48 deletions

View File

@@ -49,6 +49,9 @@ export default function HomeScreen() {
const [liveLeagueIdByMatchId, setLiveLeagueIdByMatchId] = useState< const [liveLeagueIdByMatchId, setLiveLeagueIdByMatchId] = useState<
Record<string, number> Record<string, number>
>({}); >({});
const [page, setPage] = useState(1);
const [total, setTotal] = useState(0);
const [loadingMore, setLoadingMore] = useState(false);
const deviceTimeZone = useMemo(() => { const deviceTimeZone = useMemo(() => {
try { try {
@@ -96,6 +99,11 @@ export default function HomeScreen() {
} }
}, [selectedSportId, selectedDate]); }, [selectedSportId, selectedDate]);
useEffect(() => {
setPage(1);
setTotal(0);
}, [selectedSportId, selectedDate, state.selectedLeagueKey]);
const timezoneLabel = useMemo(() => { const timezoneLabel = useMemo(() => {
// 仅展示 UTC 偏移(不展示时区名) // 仅展示 UTC 偏移(不展示时区名)
const offsetMin = -now.getTimezoneOffset(); const offsetMin = -now.getTimezoneOffset();
@@ -303,8 +311,8 @@ export default function HomeScreen() {
try { try {
if (selectedSportId !== null) { if (selectedSportId !== null) {
setLoadingLeagues(true); setLoadingLeagues(true);
const list = await fetchLeagues(selectedSportId, ""); const res = await fetchLeagues({ sportId: selectedSportId });
setLeagues(list); setLeagues(res.list);
} }
} catch (e) { } catch (e) {
console.error(e); console.error(e);
@@ -316,11 +324,16 @@ export default function HomeScreen() {
const loadMatches = async (sportId: number) => { const loadMatches = async (sportId: number) => {
setLoading(true); setLoading(true);
try { try {
const list = await fetchTodayMatches( const res = await fetchTodayMatches({
sportId, sportId,
selectedDate, date: selectedDate,
deviceTimeZone, timezone: deviceTimeZone,
); leagueKey: state.selectedLeagueKey || "",
page: 1,
pageSize: 50,
});
setPage(1);
setTotal(res.total);
const normalizeDate = (d: Date) => { const normalizeDate = (d: Date) => {
const year = d.getFullYear(); const year = d.getFullYear();
@@ -333,7 +346,7 @@ export default function HomeScreen() {
const selectedStr = normalizeDate(selectedDate); const selectedStr = normalizeDate(selectedDate);
const shouldMergeLive = selectedStr === todayStr; const shouldMergeLive = selectedStr === todayStr;
let merged: Match[] = list.map((m) => ({ let merged: Match[] = res.list.map((m) => ({
...m, ...m,
date: m.date || selectedStr, date: m.date || selectedStr,
sportId: m.sportId ?? sportId, sportId: m.sportId ?? sportId,
@@ -402,11 +415,9 @@ export default function HomeScreen() {
let listWithFavStatus = merged; let listWithFavStatus = merged;
if (token) { if (token) {
// 直接传递 match.id 查询是否收藏,并更新列表状态
listWithFavStatus = await Promise.all( listWithFavStatus = await Promise.all(
merged.map(async (m) => { merged.map(async (m) => {
try { try {
// 查询比赛是否已被收藏
const favRes = await checkFavorite("match", m.id); const favRes = await checkFavorite("match", m.id);
return { ...m, fav: favRes.isFavorite }; return { ...m, fav: favRes.isFavorite };
} catch (error) { } catch (error) {
@@ -434,6 +445,41 @@ export default function HomeScreen() {
} }
}; };
const loadMoreMatches = async () => {
if (loadingMore || loading) return;
if (!selectedSportId) return;
if (matches.length >= total) return;
setLoadingMore(true);
try {
const nextPage = page + 1;
const res = await fetchTodayMatches({
sportId: selectedSportId,
date: selectedDate,
timezone: deviceTimeZone,
leagueKey: state.selectedLeagueKey || "",
page: nextPage,
pageSize: 50,
});
setPage(nextPage);
setTotal(res.total);
setMatches((prev) => {
const byId = new Map<string, Match>();
prev.forEach((m) => byId.set(m.id, m));
res.list.forEach((m) => {
if (!byId.has(m.id)) byId.set(m.id, m);
});
return Array.from(byId.values());
});
} catch (e) {
console.error(e);
} finally {
setLoadingMore(false);
}
};
const handleFavoriteToggle = (matchId: string, isFav: boolean) => { const handleFavoriteToggle = (matchId: string, isFav: boolean) => {
setMatches((prev) => { setMatches((prev) => {
const updated = prev.map((m) => const updated = prev.map((m) =>
@@ -558,6 +604,15 @@ export default function HomeScreen() {
renderItem={({ item }) => ( renderItem={({ item }) => (
<MatchCard match={item} onFavoriteToggle={handleFavoriteToggle} /> <MatchCard match={item} onFavoriteToggle={handleFavoriteToggle} />
)} )}
onEndReached={loadMoreMatches}
onEndReachedThreshold={0.4}
ListFooterComponent={
loadingMore ? (
<View style={styles.footer}>
<ActivityIndicator size="small" color={Colors[theme].tint} />
</View>
) : null
}
contentContainerStyle={styles.listContent} contentContainerStyle={styles.listContent}
ListEmptyComponent={ ListEmptyComponent={
<View style={styles.center}> <View style={styles.center}>
@@ -650,4 +705,9 @@ const styles = StyleSheet.create({
padding: 16, padding: 16,
paddingTop: 8, paddingTop: 8,
}, },
footer: {
paddingVertical: 16,
alignItems: "center",
justifyContent: "center",
},
}); });

View File

@@ -115,22 +115,22 @@ export const fetchCountries = async (): Promise<Country[]> => {
} }
}; };
export const fetchLeagues = async ( export const fetchLeagues = async (params: {
sportId: number, sportId?: number;
countryKey: string countryKey?: string;
): Promise<League[]> => { date?: string;
page?: number;
pageSize?: number;
sortBy?: "name" | "matchCount" | "createdAt";
sortOrder?: "asc" | "desc";
}): Promise<ApiListResponse<League>> => {
try { try {
const response = await apiClient.get<ApiResponse<ApiListResponse<League>>>( const response = await apiClient.get<ApiResponse<ApiListResponse<League>>>(
API_ENDPOINTS.LEAGUES, API_ENDPOINTS.LEAGUES,
{ { params }
params: {
sportId,
countryKey,
},
}
); );
if (response.data.code === 0) { if (response.data.code === 0) {
return response.data.data.list; return response.data.data;
} }
throw new Error(response.data.message); throw new Error(response.data.message);
} catch (error) { } catch (error) {
@@ -139,48 +139,54 @@ export const fetchLeagues = async (
} }
}; };
export const fetchTodayMatches = async ( export const fetchTodayMatches = async (options: {
sportId: number, sportId: number;
date?: Date | string, date?: Date | string;
timezone?: string timezone?: string;
): Promise<Match[]> => { leagueKey?: string;
page?: number;
pageSize?: number;
}): Promise<ApiListResponse<Match>> => {
try { try {
const params: { sportId: number; date?: string; timezone?: string } = { const params: {
sportId, sportId: number;
date?: string;
timezone?: string;
leagueKey?: string;
page?: number;
pageSize?: number;
} = {
sportId: options.sportId,
leagueKey: options.leagueKey,
page: options.page,
pageSize: options.pageSize,
}; };
// 如果提供了日期,格式化为 YYYY-MM-DD 格式 if (options.date) {
if (date) { if (options.date instanceof Date) {
let dateStr: string; const year = options.date.getFullYear();
if (date instanceof Date) { const month = String(options.date.getMonth() + 1).padStart(2, "0");
const year = date.getFullYear(); const day = String(options.date.getDate()).padStart(2, "0");
const month = String(date.getMonth() + 1).padStart(2, "0"); params.date = `${year}-${month}-${day}`;
const day = String(date.getDate()).padStart(2, "0");
dateStr = `${year}-${month}-${day}`;
} else { } else {
dateStr = date; params.date = options.date;
} }
params.date = dateStr;
} }
// 如果提供了时区,传给后端;不传则由后端使用本地时区 if (options.timezone) {
if (timezone) { params.timezone = options.timezone;
params.timezone = timezone;
} }
const response = await apiClient.get<ApiResponse<ApiListResponse<Match>>>( const response = await apiClient.get<ApiResponse<ApiListResponse<Match>>>(
API_ENDPOINTS.MATCHES_TODAY, API_ENDPOINTS.MATCHES_TODAY,
{ { params }
params,
}
); );
if (response.data.code === 0) { if (response.data.code === 0) {
return response.data.data.list; return response.data.data;
} }
throw new Error(response.data.message); throw new Error(response.data.message);
} catch (error) { } catch (error) {
console.error("Fetch matches error:", error); console.error("Fetch matches error:", error);
// Let the caller handle errors; rethrow the original error
throw error; throw error;
} }
}; };
@@ -214,9 +220,9 @@ export const fetchLiveScore = async (
// }); // });
try { try {
const params: { sport_id: number; league_id?: number; timezone?: string } = const params: { sport_id: number; league_id?: number; timezone?: string } =
{ {
sport_id: sportId, sport_id: sportId,
}; };
if (leagueId) { if (leagueId) {
params.league_id = leagueId; params.league_id = leagueId;

View File

@@ -152,6 +152,7 @@ export interface League {
isActive: boolean; isActive: boolean;
createdAt: string; createdAt: string;
updatedAt: string; updatedAt: string;
matchCount?: number;
} }
export interface GoalEvent { export interface GoalEvent {