MutationCache 是用于存储变更 (mutations) 的容器。
通常情况下,您不会直接与 MutationCache 交互,而是通过 QueryClient 进行操作。
import { MutationCache } from '@tanstack/react-query'
const mutationCache = new MutationCache({
onError: (error) => {
console.log(error)
},
onSuccess: (data) => {
console.log(data)
},
})
import { MutationCache } from '@tanstack/react-query'
const mutationCache = new MutationCache({
onError: (error) => {
console.log(error)
},
onSuccess: (data) => {
console.log(data)
},
})
其提供的方法包括:
配置项
MutationCache 上的 onError、onSuccess、onSettled 和 onMutate 回调可用于全局处理这些事件。它们与提供给 QueryClient 的 defaultOptions 不同,原因在于:
getAll 返回缓存中的所有变更操作。
注意:大多数应用通常不需要此方法,但在需要获取变更操作的更多信息时可能会派上用场
const mutations = mutationCache.getAll()
const mutations = mutationCache.getAll()
返回值
subscribe 方法可用于订阅整个变更缓存,并在缓存发生安全/已知的更新(如变更状态更改或变更操作被更新、添加或删除)时收到通知。
const callback = (event) => {
console.log(event.type, event.mutation)
}
const unsubscribe = mutationCache.subscribe(callback)
const callback = (event) => {
console.log(event.type, event.mutation)
}
const unsubscribe = mutationCache.subscribe(callback)
配置项
返回值
clear 方法可用于完全清空缓存并重新开始。
mutationCache.clear()
mutationCache.clear()