根据API Reference,您需要将enabled
选项更改为false以禁用查询自动运行。然后你手动重新获取。
// emulates axios/fetch since useQuery expectes a Promise
const emulateFetch = _ => {
return new Promise(resolve => {
resolve([{ data: "ok" }]);
});
};
const handleClick = () => {
// manually refetch
refetch();
};
const { data, refetch } = useQuery("key", emulateFetch, {
refetchOnWindowFocus: false,
enabled: false // turned off by default, manual refetch is needed
});
return (
<div>
<button onClick={handleClick}>Click me</button>
{JSON.stringify(data)}
</div>
);
工作沙箱在这里。
奖励:您可以将任何返回布尔值的东西传递给enabled
. 这样您就可以创建依赖/串行查询。
// Get the user
const { data: user } = useQuery(['user', email], getUserByEmail)
// Then get the user's projects
const { isIdle, data: projects } = useQuery(
['projects', user.id],
getProjectsByUser,
{
// `user` would be `null` at first (falsy),
// so the query will not execute until the user exists
enabled: user,
}
)