过滤器
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)返回一个布尔值,指示某个修改是否匹配所提供的修改过滤器集合。