简体   繁体   English

如何在组件呈现之前不获取片段数据反应 GraphQL

[英]how to not fetch fragment data until component renders react GraphQL

I thought that relay modern implemented a system whereby it would not try to fetch data until it was rendering the component that declared it.我认为现代中继实现了一个系统,它在渲染声明它的组件之前不会尝试获取数据。 I am talking about fragment components.我说的是片段组件。 I have tried to test this but it is fetching all the data.我试图对此进行测试,但它正在获取所有数据。

import React from "react";
import { Environment, Network, RecordSource, Store } from "relay-runtime";
import {
  RelayEnvironmentProvider,
} from "react-relay/hooks";
import "./App.css";
import QueryLoaderComponent from "./QueryLoaderComponent";
import QueryComponent from "./QueryComponent";

async function fetchGraphQL(text: string, variables: Record<any, any>) {

  // Fetch data from GitHub's GraphQL API:
  const response = await fetch("https://countries.trevorblades.com/", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      query: text,
      variables,
    }),
  });

  // Get the response as JSON
  return await response.json();
}

async function fetchRelay(params: any, variables: any) {
  console.log(
    `fetching query ${params.name} with ${JSON.stringify(variables)}`
  );
  return fetchGraphQL(params.text, variables);
}

// Export a singleton instance of Relay Environment configured with our network function:
const environment = new Environment({
  network: Network.create(fetchRelay),
  store: new Store(new RecordSource()),
});

function App() {
  
  return (
    <RelayEnvironmentProvider environment={environment}>
      {/* <QueryLoaderComponent /> */}
      <QueryComponent />
    </RelayEnvironmentProvider>
  );
}

export default App;
import { useState } from "react";
// @ts-ignore
import graphql from "babel-plugin-relay/macro";
import { QueryComponentQuery } from "./__generated__/QueryComponentQuery.graphql";
import { PreloadedQuery, useLazyLoadQuery, usePreloadedQuery } from "react-relay";
// import FragmentComponent from "./FragmentComponent";

const query = graphql`
  query QueryComponentQuery($id: ID!) {
    country(code: $id) {
      name
      ...FragmentComponent_country
    }
  }
`;

interface Props {
  // queryRef: PreloadedQuery<QueryComponentQuery>;
}

const QueryComponent = ({
  // queryRef
}: Props) => {
  const data = useLazyLoadQuery<QueryComponentQuery>(query, { id: "US"});
  const [showContinent, setShowContinent] = useState(false);
  return (
    <div>
      <button onClick={() => setShowContinent(!showContinent)}>
        {showContinent ? "Hide" : "Show"} continent
      </button>
      <h1>{data.country?.name}</h1>
      {/* <ul>
        {data.countries.map((country: any) => (
          <li key={country.name}>
            {country.name}{" "}
            {showContinent && <FragmentComponent country={country} />}
          </li>
        ))}
      </ul> */}
    </div>
  );
};

export default QueryComponent;
import { useFragment } from "react-relay";
// @ts-ignore
import graphql from "babel-plugin-relay/macro";
import { FragmentComponent_country$key } from "./__generated__/FragmentComponent_country.graphql";

export const fragment = graphql`
  fragment FragmentComponent_country on Country {
    continent {
      name
    }
  }
`;

interface Props {
  country: FragmentComponent_country$key;
}

const FragmentComponent = ({ country }: Props) => {
  const data = useFragment(fragment, country);
  return <div>{data.continent.name}</div>;
};

export default FragmentComponent;

this is fetching the data for the fragment component even though it is not rendering the fragment component.即使它没有呈现片段组件,它也会为片段组件获取数据。 is there a way to defer it until it is rendering the component?有没有办法将它推迟到它渲染组件?

use利用

React Suspense反应悬念

on the fragment or anywhere where fetching happens as wrapper在片段或作为包装器进行提取的任何地方

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM