import { useState, useCallback, useRef } from 'react'; interface PaginationResult { list: T[]; setList: React.Dispatch>; loading: boolean; hasMore: boolean; total: number; loadMore: () => Promise; refresh: () => Promise; } export function usePagination( fetcher: (page: number, pageSize: number) => Promise<{ data: T[]; total: number }>, pageSize = 10, ): PaginationResult { const [list, setList] = useState([]); 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 { // 错误由调用方处理 } 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 { // 错误由调用方处理 } finally { loadingRef.current = false; setLoading(false); } }, [fetcher, pageSize]); return { list, setList, loading, hasMore, total, loadMore, refresh }; }