React-Query:单击按钮时如何使用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())}}/> 的事情,但是如何管理返回的数据和状态……

原文由 Leem.fin 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 643
1 个回答

根据 API Reference ,您需要将 enabled 选项更改为 false 以禁止查询自动运行。然后你手动重新获取。

 // emulates a fetch (useQuery expects a Promise)
const emulateFetch = _ => {
  return new Promise(resolve => {
    resolve([{ data: "ok" }]);
  });
};

const handleClick = () => {
  // manually refetch
  refetch();
};

const { data, refetch } = useQuery("my_key", emulateFetch, {
  refetchOnWindowFocus: false,
  enabled: false // disable this query from automatically running
});

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,
  }
)

原文由 Nicolas Hevia 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题