React-Query:单击按钮时如何使用查询

时间:2020-06-12 08:43:25

标签: 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())}}/>的事情,但是如何管理返回的数据和状态...

5 个答案:

答案 0 :(得分:5)

看起来文档已更改,并且现在缺少手动查询部分。但是,查看useQuery API,您可能需要将enabled设置为false,然后在按下按钮时使用refetch手动查询。您可能还想使用force: true进行查询,而不考虑数据是否新鲜。

答案 1 :(得分:4)

根据basic.compund/4,您需要将enabled选项更改为 false ,以禁止查询自动运行。然后您手动重新提取。

// 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>
);

工作沙箱API Reference

奖金:您可以传递任何将布尔值返回enabled的值。 这样,您可以创建here

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

答案 2 :(得分:1)

您必须传递manual: true参数选项,以便查询不会在装入时获取。另外,您应该传递fetchData而不带括号,以便传递函数引用而不是值。 要调用查询,请使用refetch()。

const {status, data, error, refetch} = useQuery(myKey, fetchData, {
      manual: true,
    });

const onClick = () => { refetch() }

有关更多信息,请参阅react-query文档上的手动查询部分 https://github.com/tannerlinsley/react-query#manual-querying

答案 3 :(得分:0)

如果您想触发多次重新获取,还有另一种方法可以做到这一点。

const [fetch, setFetch] = useState(null);
const query = useQuery(["endpoint", fetch], fetchData);

const refetch = () => setFetch(Date.now());

// call the refetch when handling click.

如果你想重新获取多个实体,你可以有一个顶级的 useState ,例如 fetchAll 和:

...
const query = useQuery(["endpoint", fetch, fetchAll], fetchData);
...

如果您按下按钮以获取所有内容,也会触发此代码。

答案 4 :(得分:0)

你可以试试这个版本:

const fetchData = async()=>{...}

// it starts fetching data from backend with this line of code
const {status, data, error, refetch } = useQuery(
myKey, 
fetchData(),
{
  enabled: false,
}
);
const onClick = () => { refetch() }
// then use onClick where you need it

来自文档 Doc

enabled: boolean

  • 将此设置为 false 可禁用此查询自动运行。
  • 可用于相关查询。

refetch: (options: { throwOnError: boolean, cancelRefetch: boolean }) => Promise<UseQueryResult>

  • 手动重新获取查询的函数。
  • 如果查询出错,则只会记录错误。如果您想抛出错误,请传递 throwOnError: true option
  • 如果 cancelRefetchtrue,则在发出新请求之前将取消当前请求