fix: 修复分页功能

This commit is contained in:
龙大 2026-03-22 19:27:52 +08:00
parent 2c0056c827
commit 1fdc27a9b4
1 changed files with 29 additions and 40 deletions

View File

@ -17,7 +17,7 @@ export default function List() {
const [isAdmin, setIsAdmin] = useState(false)
const [page, setPage] = useState(1)
const [hasMore, setHasMore] = useState(true)
const [initialLoad, setInitialLoad] = useState(true)
const [loadingMore, setLoadingMore] = useState(false)
useEffect(() => {
//
@ -49,19 +49,7 @@ export default function List() {
setFilter('')
setFilterType('')
}
//
const handleScroll = () => {
if (loading || !hasMore) return
const scrollTop = window.scrollY || document.documentElement.scrollTop
const scrollHeight = document.documentElement.scrollHeight
const clientHeight = document.documentElement.clientHeight
if (scrollTop + clientHeight >= scrollHeight - 100) {
fetchCollections(true)
}
}
window.addEventListener('scroll', handleScroll)
return () => window.removeEventListener('scroll', handleScroll)
fetchCollections()
}
handleHashChange()
@ -74,21 +62,27 @@ export default function List() {
}
}, [])
const fetchCollections = async (reset = false) => {
const token = localStorage.getItem('token')
const currentPage = reset ? 1 : page
try {
if (reset) {
setCollections([])
setPage(1)
setLoading(true)
setInitialLoad(true)
} else {
setLoading(true)
//
useEffect(() => {
const handleScroll = () => {
if (loading || loadingMore || !hasMore) return
const scrollTop = window.scrollY || document.documentElement.scrollTop
const scrollHeight = document.documentElement.scrollHeight
const clientHeight = document.documentElement.clientHeight
if (scrollTop + clientHeight >= scrollHeight - 100) {
fetchCollections(false)
}
}
const res = await fetch(`/api/collections?page=${currentPage}&limit=50`, {
window.addEventListener('scroll', handleScroll)
return () => window.removeEventListener('scroll', handleScroll)
}, [loading, loadingMore, hasMore, page])
const fetchCollections = async () => {
// set loading based on reset
const token = localStorage.getItem('token')
try {
const res = await fetch('/api/collections?page=1&limit=50', {
headers: token ? { 'Authorization': 'Bearer ' + token } : {}
})
@ -107,18 +101,6 @@ export default function List() {
list = list.items
}
//
if (reset) {
setCollections(list || [])
} else {
setCollections(prev => [...prev, ...(list || [])])
}
//
const receivedCount = list ? list.length : 0
setHasMore(receivedCount >= 50)
if (!initialLoad) setPage(prev => prev + 1)
//
// IDURL
if (userIdFilter) {
@ -157,7 +139,14 @@ export default function List() {
console.log(`筛选:${filterType} = ${filter}, 结果:${list.length}`)
}
setCollections(list || [])
# 分页处理
if (page === 1) {
setCollections(list || [])
} else {
setCollections(prev => [...prev, ...(list || [])])
}
setHasMore((list || []).length >= 50)
if (page > 1) setPage(p => p + 1)
} catch (e) {
console.error('Fetch collections error:', e)
//