使查询失效只是成功了一半。知道何时使它们失效是另一半。通常,当你的应用程序中的 mutation 成功时,很可能你的应用程序中存在相关的查询需要失效,并可能需要重新获取以考虑来自你的 mutation 的新更改。
例如,假设我们有一个 mutation 来发布新的 todo
const mutation = useMutation({ mutationFn: postTodo })
const mutation = useMutation({ mutationFn: postTodo })
当成功的 postTodo mutation 发生时,我们可能希望所有 todos 查询都失效,并可能重新获取以显示新的 todo 项。要做到这一点,你可以使用 useMutation 的 onSuccess 选项和 client 的 invalidateQueries 函数
import { useMutation, useQueryClient } from '@tanstack/react-query'
const queryClient = useQueryClient()
// When this mutation succeeds, invalidate any queries with the `todos` or `reminders` query key
const mutation = useMutation({
mutationFn: addTodo,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['todos'] })
queryClient.invalidateQueries({ queryKey: ['reminders'] })
},
})
import { useMutation, useQueryClient } from '@tanstack/react-query'
const queryClient = useQueryClient()
// When this mutation succeeds, invalidate any queries with the `todos` or `reminders` query key
const mutation = useMutation({
mutationFn: addTodo,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['todos'] })
queryClient.invalidateQueries({ queryKey: ['reminders'] })
},
})
你可以使用 useMutation hook 中提供的任何回调来连接你的失效操作