框架
版本

过滤器

TanStack Query 中的某些方法接受 QueryFiltersMutationFilters 对象。

Query 过滤器

查询过滤器是一个对象,其中包含用于匹配查询的特定条件

tsx
// Cancel all queries
await queryClient.cancelQueries()

// Remove all inactive queries that begin with `posts` in the key
queryClient.removeQueries({ queryKey: ['posts'], type: 'inactive' })

// Refetch all active queries
await queryClient.refetchQueries({ type: 'active' })

// Refetch all active queries that begin with `posts` in the key
await queryClient.refetchQueries({ queryKey: ['posts'], type: 'active' })
// Cancel all queries
await queryClient.cancelQueries()

// Remove all inactive queries that begin with `posts` in the key
queryClient.removeQueries({ queryKey: ['posts'], type: 'inactive' })

// Refetch all active queries
await queryClient.refetchQueries({ type: 'active' })

// Refetch all active queries that begin with `posts` in the key
await 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 过滤器

mutation 过滤器是一个对象,其中包含用于匹配 mutation 的特定条件

tsx
// Get the number of all fetching mutations
await queryClient.isMutating()

// Filter mutations by mutationKey
await queryClient.isMutating({ mutationKey: ['post'] })

// Filter mutations using a predicate function
await queryClient.isMutating({
  predicate: (mutation) => mutation.state.variables?.id === 1,
})
// Get the number of all fetching mutations
await queryClient.isMutating()

// Filter mutations by mutationKey
await queryClient.isMutating({ mutationKey: ['post'] })

// Filter mutations using a predicate function
await queryClient.isMutating({
  predicate: (mutation) => mutation.state.variables?.id === 1,
})

mutation 过滤器对象支持以下属性

  • mutationKey?: MutationKey
    • 设置此属性以定义要匹配的 mutation 键。
  • exact?: boolean
    • 如果您不想通过 mutation 键包容性地搜索 mutation,则可以传递 exact: true 选项,以仅返回具有您传递的确切 mutation 键的 mutation。
  • status?: MutationStatus
    • 允许根据 mutation 的状态过滤 mutation。
  • predicate?: (mutation: Mutation) => boolean
    • 此谓词函数将用作所有匹配 mutation 的最终过滤器。如果未指定其他过滤器,则将针对缓存中的每个 mutation 评估此函数。

实用工具

matchQuery

tsx
const isMatching = matchQuery(filters, query)
const isMatching = matchQuery(filters, query)

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

matchMutation

tsx
const isMatching = matchMutation(filters, mutation)
const isMatching = matchMutation(filters, mutation)

返回一个布尔值,指示 mutation 是否与提供的 mutation 过滤器集匹配。