预取

如果您足够幸运,可能对用户将要做什么有足够的了解,从而能够在他们需要数据之前预取他们需要的数据!如果是这种情况,您可以使用 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 中指定的时间后删除并进行垃圾回收。

预取无限 Queries

无限 Queries 可以像常规 Queries 一样进行预取。默认情况下,只会预取 Query 的第一页,并将存储在给定的 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,预取将停止。