38 lines
1.0 KiB
TypeScript
38 lines
1.0 KiB
TypeScript
import { useState, useCallback } from 'react';
|
|
|
|
interface UseInfiniteScrollResult<T> {
|
|
items: T[];
|
|
loadMore: () => void;
|
|
hasMore: boolean;
|
|
isLoadingMore: boolean;
|
|
}
|
|
|
|
export function useInfiniteScroll<T>(
|
|
allItems: T[],
|
|
itemsPerPage: number = 10
|
|
): UseInfiniteScrollResult<T> {
|
|
const [currentPage, setCurrentPage] = useState(1);
|
|
const [isLoadingMore, setIsLoadingMore] = useState(false);
|
|
|
|
const totalPages = Math.ceil(allItems.length / itemsPerPage);
|
|
const hasMore = currentPage < totalPages;
|
|
const displayedItems = allItems.slice(0, currentPage * itemsPerPage);
|
|
|
|
const loadMore = useCallback(() => {
|
|
if (hasMore && !isLoadingMore) {
|
|
setIsLoadingMore(true);
|
|
// 模拟加载延迟
|
|
setTimeout(() => {
|
|
setCurrentPage(prev => prev + 1);
|
|
setIsLoadingMore(false);
|
|
}, 500);
|
|
}
|
|
}, [hasMore, isLoadingMore]);
|
|
|
|
return {
|
|
items: displayedItems,
|
|
loadMore,
|
|
hasMore,
|
|
isLoadingMore
|
|
};
|
|
}
|