Apollo GraphQL React - 如何查询点击?

atk*_*yla 55 reactjs graphql apollostack

在阿波罗阵营文档http://dev.apollodata.com/react/queries.html#basics有被示出的组件时自动获取的例子,但我想运行查询一个按钮被点击时.我看到一个示例,当单击一个按钮时"重新"获取查询,但我不希望它最初查询.我看到有一种方法可以调用突变,但是你如何调用查询?

stu*_*ilo 66

您可以通过使用经过参考阿波罗客户做withApollo更高阶的分量,如下记载: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);
Run Code Online (Sandbox Code Playgroud)

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

  • 在apollo 2.1中,您可以使用<ApolloConsumer />组件https://www.apollographql.com/docs/react/api/react-apollo.html#apollo-consumer ...也是---> https:// www .apollographql.com / docs / react / essentials / queries.html#manual-query (3认同)
  • 我想将其用于搜索栏 (2认同)

Dan*_*den 5

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

client.query

第一种方法是调用ApolloClientquery方法。这将返回一个Promise,它将解决查询的结果。您可以使用withApollo HOC 获取对客户端的引用:

class MyComponent extends React.Component {
  handleClick() {
    const { data } = await this.props.client.query({
      query: gql`...`,
      variables: { ... },
    })
    ...
  }
  ...
}

withApollo(MyComponent)
Run Code Online (Sandbox Code Playgroud)

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

const MyComponent = () => (
  <ApolloConsumer>
    {client => {
      ...
    }
  </ApolloConsumer>
)
Run Code Online (Sandbox Code Playgroud)

useApolloClient挂钩:

const MyComponent = () => {
  const client = useApolloClient()
  ...
}
Run Code Online (Sandbox Code Playgroud)

useLazyQuery

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

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