The QueryCache 是 TanStack Query 的存储机制。它存储了其包含的查询的所有数据、元信息和状态。
Normally, you will not interact with the QueryCache directly and instead use the QueryClient 来操作特定的缓存。
import { QueryCache } from '@tanstack/react-query'
const queryCache = new QueryCache({
onError: (error) => {
console.log(error)
},
onSuccess: (data) => {
console.log(data)
},
onSettled: (data, error) => {
console.log(data, error)
},
})
const query = queryCache.find(['posts'])
import { QueryCache } from '@tanstack/react-query'
const queryCache = new QueryCache({
onError: (error) => {
console.log(error)
},
onSuccess: (data) => {
console.log(data)
},
onSettled: (data, error) => {
console.log(data, error)
},
})
const query = queryCache.find(['posts'])
其可用的方法有
选项
find 是一个稍微高级的同步方法,可用于从缓存中获取现有的查询实例。此实例不仅包含查询的所有状态,还包含所有实例以及查询的底层细节。如果查询不存在,将返回 undefined。
注意:这通常不是大多数应用程序所必需的,但在罕见情况下需要有关查询的更多信息时(例如,查看 query.state.dataUpdatedAt 时间戳以确定查询是否足够新鲜以用作初始值)可能会派上用场
const query = queryCache.find(queryKey)
const query = queryCache.find(queryKey)
选项
返回值
findAll 是一个更高级的同步方法,可用于从缓存中获取与查询键部分匹配的现有查询实例。如果查询不存在,将返回空数组。
注意:这通常不是大多数应用程序所必需的,但在罕见情况下需要有关查询的更多信息时可能会派上用场
const queries = queryCache.findAll(queryKey)
const queries = queryCache.findAll(queryKey)
选项
返回值
The subscribe 方法可用于订阅整个查询缓存,并获知对缓存的安全/已知更新,例如查询状态更改或查询被更新、添加或删除
const callback = (event) => {
console.log(event.type, event.query)
}
const unsubscribe = queryCache.subscribe(callback)
const callback = (event) => {
console.log(event.type, event.query)
}
const unsubscribe = queryCache.subscribe(callback)
选项
返回值
The clear 方法可用于完全清除缓存并重新开始。
queryCache.clear()
queryCache.clear()
要更好地理解 QueryCache 的内部工作原理,请查看社区资源中的 #18: Inside React Query。