首页 > 解决方案 > 在 React 应用程序中,是优先于 client.query 执行查询?

问题描述

我正在开发一个 React 项目,其中使用 apollo 客户端执行如下查询:

const client = new ApolloClient({
    link: link,
    cache: new InMemoryCache(),
});

client.query({ query: gql`{ hello }` })

但我见过的大多数例子看起来像:

import gql from "graphql-tag";
import { Query } from "react-apollo";

const GET_DOGS = gql`
  {
    dogs {
      id
      breed
    }
  }
`;

const Dogs = ({ onDogSelected }) => (
  <Query query={GET_DOGS}>
    {({ loading, error, data }) => {
      if (loading) return "Loading...";
      if (error) return `Error! ${error.message}`;

      return (
        <select name="dog" onChange={onDogSelected}>
          {data.dogs.map(dog => (
            <option key={dog.id} value={dog.breed}>
              {dog.breed}
            </option>
          ))}
        </select>
      );
    }}
  </Query>
);

对于 React 应用程序,什么时候一种方法优于另一种?<Query>语法总是首选吗?

标签: graphqlapolloreact-apollo

解决方案


query直接在客户端调用的用例,但是的,使用 Query 组件是模式。从文档:

当 React 挂载一个 Query 组件时,Apollo Client 会自动触发你的查询。如果您想延迟触发查询,直到用户执行操作(例如单击按钮),该怎么办?对于这种情况,我们希望使用 ApolloConsumer 组件并直接调用 client.query() 代替。... 以这种方式获取非常冗长,因此我们建议尽可能尝试使用 Query 组件!

Both the signature of the Query component's render prop function and the value the query call Promise resolves to are of the type ApolloQueryResult. However, there's some fine differences between the two. For example, using the Component means the loading value will be updated multiple times to reflect the status of the query, while you don't get the same functionality when using the client directly.

Generally, using the client directly also means you'll need to persist the results in some other component's state as opposed to just using the values provided by the render props function.

If a query needs to be triggered manually, especially if the query results will not be persisted in state, it's perfectly fine to use the client directly. Otherwise, you're probably better off using the Query component.


推荐阅读