在事件处理程序中,不能直接使用useQuery。相反,可以在组件级别使用useQuery,在事件处理程序中可以使用fetch(或axios等)来手动触发查询并更新数据。
例如:
import { useQuery } from 'react-query';
import { useForm } from 'react-hook-form';
function App() {
const { register, handleSubmit } = useForm();
const { data: userData, refetch } = useQuery('userData', getUserData);
const onSubmit = (formValues) => {
// 在此处手动调用fetch
fetch(`/user/${userData.id}`, {
method: 'PUT',
body: JSON.stringify(formValues),
headers: {
'Content-Type': 'application/json',
},
})
.then(() => {
// 成功保存数据后重新获取用户数据
refetch();
})
.catch((error) => {
console.error(error);
});
};
return (
);
}
function getUserData() {
return fetch('/user')
.then((res) => res.json())
.then((data) => data);
}
export default App;