译零 TransZero · TanStack Query 中文文档
主站

查询函数

更新于 2026-11-02 Solid 查看英文原文 ↗

查询函数可以是返回 Promise 的任意函数。该 Promise 应当要么解析出数据,要么抛出错误。

成功时,解析值可以是除 undefined 以外的任何值。解析为 undefined 的查询将被视为失败。若要在查询缓存中将“空值”作为成功结果存储,请改用解析 null。

以下所有配置均为有效的查询函数:

TypeScript
1useQuery(() => ({ queryKey: ['todos'], queryFn: fetchAllTodos }))2useQuery(() => ({3  queryKey: ['todos', todoId],4  queryFn: () => fetchTodoById(todoId),5}))6useQuery(() => ({7  queryKey: ['todos', todoId],8  queryFn: async () => {9    const data = await fetchTodoById(todoId)10    return data11  },12}))13useQuery(() => ({14  queryKey: ['todos', todoId],15  queryFn: ({ queryKey }) => fetchTodoById(queryKey[1]),16}))

错误处理与抛出

为了让 TanStack Query 判定查询发生错误,查询函数必须抛出错误或返回一个被拒绝的 Promise。查询函数中抛出的任何错误都将被持久化到查询的 error 状态中。

TypeScript
1const todosQuery = useQuery(() => ({2  queryKey: ['todos', todoId],3  queryFn: async () => {4    if (somethingGoesWrong) {5      throw new Error('Oh no!')6    }7    if (somethingElseGoesWrong) {8      return Promise.reject(new Error('Oh no!'))9    }10 11    return data12  },13}))

与 fetch 及其他默认不抛出错误的客户端配合使用

虽然 axios 或 graphql-request 等大多数工具会在 HTTP 请求失败时自动抛出错误,但 fetch 等部分工具默认不会抛出错误。若如此,你需自行抛出错误。以下是使用流行的 fetch API 实现该操作的一种简单方式:

TypeScript
1useQuery(() => ({2  queryKey: ['todos', todoId],3  queryFn: async () => {4    const response = await fetch('/todos/' + todoId)5    if (!response.ok) {6      throw new Error('Network response was not ok')7    }8    return response.json()9  },10}))

查询函数变量

查询键不仅用于唯一标识所获取的数据,还会作为 QueryFunctionContext 的一部分便捷地传入查询函数。尽管并非总是必需,但这使得你在需要时可将查询函数提取出来:

TypeScript
1function Todos(props) {2  const todosQuery = useQuery(() => ({3    queryKey: ['todos', { status: props.status, page: props.page }],4    queryFn: fetchTodoList,5  }))6}7 8// Access the key, status and page variables in your query function!9function fetchTodoList({ queryKey }) {10  const [_key, { status, page }] = queryKey11  return new Promise()12}

QueryFunctionContext

QueryFunctionContext 是传递给每个查询函数的对象,其组成包括:

  • queryKey: QueryKey:查询键
  • client: QueryClient:QueryClient
  • signal?: AbortSignal
  • meta: Record<string, unknown> | undefined
    • 一个可选字段,可用于填充有关查询的额外信息

此外,无限查询 还会收到以下选项:

  • pageParam: TPageParam
    • 用于获取当前页的页码参数
  • direction: 'forward' | 'backward'
    • 已弃用
    • 当前页获取的方向
    • 若要获取当前页获取的方向,请在 pageParam 中添加 direction 字段,来源为 getNextPageParam 和 getPreviousPageParam。

本页为 TanStack Query 文档(Solid 版)的非官方中文翻译,原文由上游团队维护,遵循 MIT 许可。 译文如有偏差,以英文原文为准。

译自上游 59d11de