如果您足够幸运,可能对用户将要做什么有足够的了解,从而能够在他们需要数据之前预取他们需要的数据!如果是这种情况,您可以使用 prefetchQuery 方法来预取查询结果并将其放入缓存中
const prefetchTodos = async () => {
// The results of this query will be cached like a normal query
await queryClient.prefetchQuery({
queryKey: ['todos'],
queryFn: fetchTodos,
})
}
const prefetchTodos = async () => {
// The results of this query will be cached like a normal query
await queryClient.prefetchQuery({
queryKey: ['todos'],
queryFn: fetchTodos,
})
}
无限 Queries 可以像常规 Queries 一样进行预取。默认情况下,只会预取 Query 的第一页,并将存储在给定的 QueryKey 下。如果您想预取多页,可以使用 pages 选项,在这种情况下,您还必须提供一个 getNextPageParam 函数
const prefetchProjects = async () => {
// The results of this query will be cached like a normal query
await queryClient.prefetchInfiniteQuery({
queryKey: ['projects'],
queryFn: fetchProjects,
initialPageParam: 0,
getNextPageParam: (lastPage, pages) => lastPage.nextCursor,
pages: 3, // prefetch the first 3 pages
})
}
const prefetchProjects = async () => {
// The results of this query will be cached like a normal query
await queryClient.prefetchInfiniteQuery({
queryKey: ['projects'],
queryFn: fetchProjects,
initialPageParam: 0,
getNextPageParam: (lastPage, pages) => lastPage.nextCursor,
pages: 3, // prefetch the first 3 pages
})
}
上面的代码将尝试按顺序预取 3 页,并且将为每一页执行 getNextPageParam 以确定要预取的下一页。如果 getNextPageParam 返回 undefined,预取将停止。