框架
版本

过滤器

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

查询过滤器

查询过滤器是具有特定条件以匹配查询的对象

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
    • 此谓词函数将用作所有匹配查询的最终过滤器。如果没有指定其他过滤器,此函数将针对缓存中的每个查询进行评估。

突变过滤器

突变过滤器是具有特定条件以匹配突变的对象

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,
})

突变过滤器对象支持以下属性

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

工具

matchQuery

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

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

matchMutation

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

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