我是新手 react-query图书馆。
我知道当我想获取数据时,使用这个库我可以做这样的事情:
const fetchData = async()=>{...}
// it starts fetching data from backend with this line of code
const {status, data, error} = useQuery(myKey, fetchData());
有用。但是如何仅在单击按钮时触发数据获取? ,我知道我可能会做类似
<Button onPress={() => {useQuery(myKey, fetchData())}}/>
的事情,但是如何管理返回的数据和状态...
最佳答案
根据API Reference ,您需要更改 enabled
选项 假 禁止查询自动运行。然后你手动重新获取。
// emulates axios/fetch since useQuery expectes a Promise
const emulateFetch = async _ => {
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>
);
工作沙箱 here .奖励:您可以将任何返回 bool 值的内容传递给
enabled
.这样你就可以创建 Dependant/Serial queries .
// 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,
}
)
关于react-native - React-Query:单击按钮时如何使用Query,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62340697/