分页查询
分页查询 / 延迟查询
const result = useQuery({
queryKey: ['projects', page],
queryFn: fetchProjects,
})使用 placeholderData 实现更优的分页查询
placeholderData 实现更优的分页查询import { keepPreviousData, useQuery } from '@tanstack/react-query'
import React from 'react'
function Todos() {
const [page, setPage] = React.useState(0)
const fetchProjects = (page = 0) =>
fetch('/api/projects?page=' + page).then((res) => res.json())
const { isPending, isError, error, data, isFetching, isPlaceholderData } =
useQuery({
queryKey: ['projects', page],
queryFn: () => fetchProjects(page),
placeholderData: keepPreviousData,
})
return (
<div>
{isPending ? (
<div>加载中...</div>
) : isError ? (
<div>错误: {error.message}</div>
) : (
<div>
{data.projects.map((project) => (
<p key={project.id}>{project.name}</p>
))}
</div>
)}
<span>当前页码: {page + 1}</span>
<button
onClick={() => setPage((old) => Math.max(old - 1, 0))}
disabled={page === 0}
>
上一页
</button>
<button
onClick={() => {
if (!isPlaceholderData && data.hasMore) {
setPage((old) => old + 1)
}
}}
// 在确认有下一页之前禁用“下一页”按钮
disabled={isPlaceholderData || !data?.hasMore}
>
下一页
</button>
{isFetching ? <span> 加载中...</span> : null}
</div>
)
}使用 placeholderData 延迟无限查询结果
placeholderData 延迟无限查询结果最后更新于