Apollo GraphQL React - 如何在点击时查询?

Apollo GraphQL React - how to query on click?

在 Apollo React 文档中 http://dev.apollodata.com/react/queries.html#basics 有显示组件时自动获取的示例,但我想 运行 单击按钮时进行查询。我看到一个 "re" 在单击按钮时获取查询的示例,但我不希望它最初进行查询。我看到有一种调用突变的方法,但是你如何调用查询?

您可以通过使用 withApollo 高阶组件传递对 Apollo Client 的引用来实现,如此处记录:https://www.apollographql.com/docs/react/api/react-apollo.html#withApollo

然后,您可以在传入的对象上调用 client.query,如下所示:

class MyComponent extends React.Component {
  runQuery() {
    this.props.client.query({
      query: gql`...`,
      variables: { ... },
    });
  }

  render() { ... }
}

withApollo(MyComponent);

出于好奇,运行 查询点击事件的目的是什么?也许有更好的方法来实现基本目标。

从 3.0 版开始,您现在可以通过两种方式执行此操作。

client.query

第一种方式是调用ApolloClientquery方法。 returns 一个将解析为查询结果的 Promise。您可以使用 withApollo HOC:

获取对客户端的引用
class MyComponent extends React.Component {
  handleClick() {
    const { data } = await this.props.client.query({
      query: gql`...`,
      variables: { ... },
    })
    ...
  }
  ...
}

withApollo(MyComponent)

或者,您也可以使用 ApolloConsumer 获取客户端:

const MyComponent = () => (
  <ApolloConsumer>
    {client => {
      ...
    }
  </ApolloConsumer>
)

useApolloClient 挂钩:

const MyComponent = () => {
  const client = useApolloClient()
  ...
}

useLazyQuery

第二种方式是使用useLazyQuery钩子:

const MyComponent = () => {
  const [runQuery, { called, loading, data }] = useLazyQuery(gql`...`)
  const handleClick = () => runQuery({ variables: { ... } })
  ...
}