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

过滤器

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

TanStack Query 中的某些方法接受一个 QueryFilters 或 MutationFilters 对象。

Query Filters

查询过滤器是一个带有特定匹配条件的对象,用于匹配查询:

TypeScript
1// Cancel all queries2await queryClient.cancelQueries()3 4// Remove all inactive queries that begin with `posts` in the key5queryClient.removeQueries({ queryKey: ['posts'], type: 'inactive' })6 7// Refetch all active queries8await queryClient.refetchQueries({ type: 'active' })9 10// Refetch all active queries that begin with `posts` in the key11await queryClient.refetchQueries({ queryKey: ['posts'], type: 'active' })

查询过滤器对象支持以下属性:

  • queryKey?: QueryKey
    • 设置此属性以定义要匹配的查询键。
  • exact?: boolean
    • 如果你不希望按查询键进行包含式搜索,可以传入 exact: true 选项,仅返回与所传查询键完全匹配的查询。
  • type?: 'active' | 'inactive' | 'all'
    • 默认为 all
    • 设为 active 时,将匹配活跃查询。
    • 设为 inactive 时,将匹配非活跃查询。
  • stale?: boolean
    • 设为 true 时,将匹配过期查询。
    • 设为 false 时,将匹配新鲜查询。
  • fetchStatus?: FetchStatus
    • 设为 fetching 时,将匹配当前正在拉取的查询。
    • 设为 paused 时,将匹配本应拉取但已被 paused 的查询。
    • 设为 idle 时,将匹配未在拉取的查询。
  • predicate?: (query: Query) => boolean
    • 此谓词函数将作为最终筛选器应用于所有已匹配的查询。若未指定其他过滤器,该函数将对缓存中的每个查询进行求值。

Mutation Filters

修改过滤器是一个带有特定匹配条件的对象,用于匹配修改:

TypeScript
1// Get the number of all fetching mutations2await queryClient.isMutating()3 4// Filter mutations by mutationKey5await queryClient.isMutating({ mutationKey: ['post'] })6 7// Filter mutations using a predicate function8await queryClient.isMutating({9  predicate: (mutation) => mutation.state.variables?.id === 1,10})

修改过滤器对象支持以下属性:

  • mutationKey?: MutationKey
    • 设置此属性以定义要匹配的修改键。
  • exact?: boolean
    • 如果你不希望按修改键进行包含式搜索,可以传入 exact: true 选项,仅返回与所传修改键完全匹配的修改。
  • status?: MutationStatus
    • 允许根据修改的状态进行过滤。
  • predicate?: (mutation: Mutation) => boolean
    • 此谓词函数将作为最终筛选器应用于所有已匹配的修改。若未指定其他过滤器,该函数将对缓存中的每个修改进行求值。

工具函数

matchQuery

TypeScript
1const isMatching = matchQuery(filters, query)

返回一个布尔值,指示某个查询是否匹配所提供的查询过滤器集合。

matchMutation

TypeScript
1const isMatching = matchMutation(filters, mutation)

返回一个布尔值,指示某个修改是否匹配所提供的修改过滤器集合。

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

译自上游 59d11de