55 个文件中 82 处空 catch 块添加模块前缀日志输出: - stores: auth/health/points (7 处) - services: request/ai-chat/health/ble/* (10 处) - hooks: useLongPolling/usePagination (3 处) - pages: 核心+子包共 35 个页面 (62 处) 保留静默的 catch: secure-storage fallback、Storage 恢复、 analytics 防洪、BLE 断连清理、用户拒绝订阅等合理忽略场景
66 lines
1.9 KiB
TypeScript
66 lines
1.9 KiB
TypeScript
import { useState, useCallback, useRef } from 'react';
|
|
|
|
interface PaginationResult<T> {
|
|
list: T[];
|
|
setList: React.Dispatch<React.SetStateAction<T[]>>;
|
|
loading: boolean;
|
|
hasMore: boolean;
|
|
total: number;
|
|
loadMore: () => Promise<void>;
|
|
refresh: () => Promise<void>;
|
|
}
|
|
|
|
export function usePagination<T>(
|
|
fetcher: (page: number, pageSize: number) => Promise<{ data: T[]; total: number }>,
|
|
pageSize = 10,
|
|
): PaginationResult<T> {
|
|
const [list, setList] = useState<T[]>([]);
|
|
const [loading, setLoading] = useState(false);
|
|
const [hasMore, setHasMore] = useState(true);
|
|
const [total, setTotal] = useState(0);
|
|
const pageRef = useRef(1);
|
|
const loadingRef = useRef(false);
|
|
|
|
const loadMore = useCallback(async () => {
|
|
if (loadingRef.current || !hasMore) return;
|
|
loadingRef.current = true;
|
|
setLoading(true);
|
|
try {
|
|
const res = await fetcher(pageRef.current, pageSize);
|
|
const items = res.data || [];
|
|
setList((prev) => [...prev, ...items]);
|
|
setTotal(res.total);
|
|
setHasMore(items.length >= pageSize);
|
|
pageRef.current += 1;
|
|
} catch (err) {
|
|
console.warn('[pagination] 加载分页数据失败:', err);
|
|
} finally {
|
|
loadingRef.current = false;
|
|
setLoading(false);
|
|
}
|
|
}, [fetcher, pageSize, hasMore]);
|
|
|
|
const refresh = useCallback(async () => {
|
|
if (loadingRef.current) return;
|
|
loadingRef.current = true;
|
|
setLoading(true);
|
|
pageRef.current = 1;
|
|
setHasMore(true);
|
|
try {
|
|
const res = await fetcher(1, pageSize);
|
|
const items = res.data || [];
|
|
setList(items);
|
|
setTotal(res.total);
|
|
setHasMore(items.length >= pageSize);
|
|
pageRef.current = 2;
|
|
} catch (err) {
|
|
console.warn('[pagination] 加载分页数据失败:', err);
|
|
} finally {
|
|
loadingRef.current = false;
|
|
setLoading(false);
|
|
}
|
|
}, [fetcher, pageSize]);
|
|
|
|
return { list, setList, loading, hasMore, total, loadMore, refresh };
|
|
}
|