javascript 'react-query'在成功时变异函数未响应

ltqd579y  于 2023-01-19  发布在  Java
关注(0)|答案(3)|浏览(150)

查询,我正在做一个公告板。所以,我把值 将Form信息中title, content的值导入react-query函数onSuccess中,在该值中,console.log没有React。

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成功或失败,onSuccess,onError中的console.log应该被记录,但它没有被记录。为什么要这样做?onSuccess,onError似乎没有响应。
我不知道为什么。救命

but5z9lq

but5z9lq1#

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])
xnifntxz

xnifntxz2#

您还可以使用mutateAsync,等待异步完成,然后在特定场景中获得响应(如果需要)。

roejwanj

roejwanj3#

onSuccess / onError等方法应在useMutation钩子创建过程中定义,而不是在您根据文档调用mutate函数时定义。
https://react-query.tanstack.com/guides/mutations
你必须适应你的需要,但想法是:

export const useAddFAQPost = () => {
    return useMutation(FaqPost, {
       onSuccess: async (data: string, context: string) => {
          console.log(data);
          console.log('why not?');
       },
       onError: async (data: string, context: string) => {
          console.log(data);
       } 
    })
}

也可以在调用useAddFAQPost()时传递它

相关问题