React Apollo Client,加载仅在第一次查询时更改为 true

React Apollo Client, loading only change to true on first time query

我在同一目录中有一个简单的文件结构 (./src/)

App.js

import React from "react";
import {
  ApolloClient,
  ApolloProvider,
  createHttpLink,
  InMemoryCache,
} from "@apollo/client";
import Gql from "./Gql";

const App = () => {
  const client = new ApolloClient({
    link: createHttpLink({
      uri: "https://api.spacex.land/graphql/",
    }),
    cache: new InMemoryCache(),
  });

  return (
    <ApolloProvider client={client}>
      <Gql />
    </ApolloProvider>
  );
};

export default App;

Gql.js

import React from "react";
import { gql, useLazyQuery } from "@apollo/client";

const Gql = () => {
  const [getQuery, { loading, data, error }] = useLazyQuery(gql`
    query {
      launchesPast(limit: 10) {
        mission_name
        launch_date_local
        launch_site {
          site_name_long
        }
      }
    }
  `);

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

  return (
    <React.Fragment>
      <button
        style={{ padding: "20px" }}
        onClick={() => {
          getQuery();
        }}>
        Request Query
      </button>
      <div>Loading: {loading ? "true" : "false"}</div>
      <div>data: {JSON.stringify(data)}</div>
    </React.Fragment>
  );
};

export default Gql;

loading 变量在第一次请求时更改为 true 和 false。但是,如果我尝试在不重新加载页面的情况下一次又一次地查询它。当浏览器向 graphql 服务器发出有效的 XHR 请求时,loading 变量保持不变。

这是设计使然,useLazyQuery 挂钩只会在参数更改时 运行 因为这将防止无用的重新渲染。