预取

如果够幸运,您可能已经足够了解用户将要做什么,以至于可以在用户需要数据之前预取他们所需的数据!如果情况是这样,您可以使用 prefetchQuery 方法来预取查询结果,以便将其放入缓存中。

tsx
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,
  })
}
  • 如果该查询的新鲜数据已在缓存中,则不会获取数据。
  • 如果传递了 staleTime,例如 prefetchQuery({ queryKey: ['todos'], queryFn: fn, staleTime: 5000 }),并且数据比指定的 staleTime 旧,则将获取该查询。
  • 如果没有任何 useQuery 实例出现在预取的查询中,则在 gcTime 中指定的过期时间后,它将被删除并进行垃圾回收。

预取无限查询

无限查询可以像常规查询一样进行预取。默认情况下,仅预取查询的第一页,并将其存储在给定的 QueryKey 下。如果要预取多页,可以使用 pages 选项,在这种情况下,您还必须提供 getNextPageParam 函数。

tsx
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,则预取将停止。