gpt4 book ai didi

javascript - `react-query` 突变 onSuccess 函数没有响应

转载 作者:行者123 更新时间:2023-12-05 00:35:05 26 4
gpt4 key购买 nike

询问,
我现在正在做一个公告板。
所以,我把title, content的值在 Form信息进入react-query功能 onSuccess .在值中,console.log 没有反应。

export const useAddFAQPost = () => {
return useMutation(FaqPost)
}

export function FaqPost(data: FAQ) {
return axios.post<FAQ>('/add', data, {

})
}
  const { mutate } = useAddFAQPost()

const onSubmit = useCallback((event: React.ChangeEvent<FormEvent>) => {
event.preventDefault();
return mutate({ title, type } as FAQ), {
onSuccess: async (data: string, context: string) => {
console.log(data);
console.log('why not?');
},
onError: async (data: string, context: string) => {
console.log(data);
}
};
}, [title, type])

return (
<>
<form onSubmit={onSubmit}>
<input type="text" name="title" value={title} ... />
<option value="faq">FAQ</option>
</form>
</>
)
如果onSubmit成功或失败,console.log中的onSuccess,onError应该被记录,但是没有被记录。你为什么做这个?
onSuccess,onError 似乎没有响应。
我不知道为什么。帮助

最佳答案

accepted answer是不正确的。 onSuccess/onError 处理程序也可用于 'mutate' 方法 ( https://react-query.tanstack.com/reference/useMutation )。
这里的问题是,如果您的组件在突变完成之前卸载,这些额外的回调将不会运行。因此,您必须确保执行突变的组件不会卸载。在你的情况下:

const {
mutate
} = useAddFAQPost()

const onSubmit = useCallback((event: React.ChangeEvent < FormEvent > ) => {
event.preventDefault();
return mutate({
title,
type
}
as FAQ), {
onSuccess: async(data: string, context: string) => {
console.log(data);
console.log('why not?');
},
onError: async(data: string, context: string) => {
console.log(data);
},
onSettled: () => {
// Some unmounting action.
// eg: if you have a form in a popup or modal,
// call your close modal method here.
// onSettled will trigger once the mutation is done either it
// succeeds or errors out.
}
};
}, [title, type])

关于javascript - `react-query` 突变 onSuccess 函数没有响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70662482/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com