react-native - React-Query:单击按钮时如何使用Query

标签 react-native react-query

我是新手 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/

相关文章:

javascript - 有没有办法检查和取消检查我的示例中的 "check-boxes"?

ios - 如何在 react-native 中实现 native 模块?

react-query - 如何在 axios 中使用 react-query 突变?

android - 在 native react 中打开联系人应用程序

typescript - 如何在 typescript 中的 React Native 中设置全局变量?

javascript - 何时从服务器重新获取数据与何时仅更新状态

reactjs - 在 react 查询中获取 'isLoading' 状态未定义

reactjs - 将 react 查询的测试与测试库集成

reactjs - 我如何等待 React Query 中的突变执行?

javascript - 在对象方法内部设置超时