React Hooks 和 React Query (useQuery):仅在单击按钮时调用 API 调用/查询

Wai*_*ein 2 reactjs react-hooks react-query

我正在开发一个 React JS 项目。我正在使用 React Hooks (功能组件)和React query

我通常在功能组件中运行/执行查询,如下所示。

const ItemList = (props) => {
  let getItemsQuery = useQuery([ 'get-items' ], getItems, {
    retry: false,
    refetchOnWindowFocus: false
  });

  // The rest of the code goes here
}
Run Code Online (Sandbox Code Playgroud)

基本上,查询是在组件加载时执行的,因此 API 调用也会进行。

现在,我正在寻找一种只能在单击按钮时执行查询的方法。

return (
   <button onClick={() => {
       //make the call. The value or value might be overridden when the API call is made when the Call 2 button is clicked
    }}>Call 1</button>
   <button onClick={() => {
       //make the call. The value or value might be overridden when the API call is made when the Call 1 button is clicked
    }}>Call 2</button>
)
Run Code Online (Sandbox Code Playgroud)

正如您在上面的虚拟代码中看到的,注释解释了我想要实现的目标。我怎样才能做到这一点?

jac*_*son 6

从这个答案中得出:

import React, { useState } from "react";
import { useQuery } from "react-query";

const App = (props) => {
  const [text, setText] = useState("");

  // use your async request (axios, fetch, etc)
  // useQuery expects a Promise so we can safely use this instead
  const emulateFetch = async (_) => {
    // axios.get (...)
    console.log(`Passing ${text} to fetch`);
    return new Promise((resolve) => {
      resolve([{ data: "ok" }]);
    });
  };

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

  const { isLoading, error, data, refetch } = useQuery(
    ["key", { text }],
    emulateFetch,
    {
      refetchOnWindowFocus: false,
      enabled: false // needed to handle refetchs manually
    }
  );

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>Error: {error}</div>;

  return (
    <div>
      <p>Home page</p>
      <input
        type="text"
        value={text}
        onChange={(event) => setText(event.target.value)}
      />
      <button onClick={handleClick}>Click me</button>
      {JSON.stringify(data)}
    </div>
  );
};

export default App;
Run Code Online (Sandbox Code Playgroud)

工作沙箱