提问人:iceyisaak 提问时间:11/10/2023 更新时间:11/10/2023 访问量:16
“react-query”中的“useQueryClient()”在分离的“mutationFn”中不起作用,导致函数执行不中
`useQueryClient()` from `react-query` not working in the separated `mutationFn` causing function inexecution
问:
我正在尝试将代码与代码分开,以便代码更易于阅读。mutationFn
useMutation()
然而,事实证明,在钩子函数之外似乎不起作用。我想知道为什么会这样,以及我如何才能分离该功能并使其仍能按我最初的意图工作。useQueryClient()
useDeleteAllTasks()
使用的后端是 JSON 服务器。使用 React Query V5 和 Axios 进行抓取。
所以这是钩子中的代码,它按预期完美地工作:useDeleteAllTasks()
export const useDeleteAllTasks = () => {
const currentQuery = useQueryClient()
return useMutation({
mutationKey: ['delete-all-tasks'],
mutationFn: () => {
const prevTasks = currentQuery.getQueryData<Task[]>(['tasks'])
const taskArray = prevTasks?.map(task => task.id);
taskArray?.forEach(id => deleteTaskByID(id))
},
onSettled: () => currentQuery.invalidateQueries({ queryKey: ['tasks'] })
})
}
但我认为这也有效,但事实并非如此:
export const useDeleteAllTasks = () => {
const currentQuery = useQueryClient()
return useMutation({
mutationKey: ['delete-all-tasks'],
mutationFn: deleteAllTasks
},
onSettled: () => currentQuery.invalidateQueries({ queryKey: ['tasks'] })
})
}
const deleteAllTasks = () => {
// This logs as expected
console.log('deleteAllTasks() - 1')
// This line does NOT seem work, which causes the rest of the function to stop working.
const currentQuery = useQueryClient()
// This doesn't show up at all
console.log('deleteAllTasks() - 2')
// No response from the function beyond this line
const prevTasks = currentQuery.getQueryData<Task[]>(['tasks'])
const taskArray = prevTasks?.map(task => task.id);
taskArray?.forEach(id => deleteTaskByID(id))
console.log('deleteAllTasks() - DONE')
}
欢迎所有富有成效的建议:)
答: 暂无答案
评论