Apollo GraphQL React - 如何在点击时查询? [英] Apollo GraphQL React - how to query on click?
问题描述
在 Apollo React 文档中http://dev.apollodata.com/react/queries.html#basics 有显示组件时自动获取的示例,但我想在单击按钮时运行查询.我看到一个在单击按钮时重新"获取查询的示例,但我不希望它最初进行查询.我看到有一种方法可以调用突变,但是如何调用查询?
In the Apollo React docs http://dev.apollodata.com/react/queries.html#basics there are examples of fetching automatically when the component is shown, but I'd like to run a query when a button is clicked. I see an example to "re"fetch a query when a button is clicked, but I don't want it to query initially. I see there is a way to call mutations, but how do you call queries?
推荐答案
您可以使用 withApollo
高阶组件将引用传递给 Apollo Client,如下所述:
You can do it by passing a reference to Apollo Client using the withApollo
higher-order-component, as documented here: https://www.apollographql.com/docs/react/api/react-apollo.html#withApollo
然后,您可以对传入的对象调用 client.query
,如下所示:
Then, you can call client.query
on the passed in object, like so:
class MyComponent extends React.Component {
runQuery() {
this.props.client.query({
query: gql`...`,
variables: { ... },
});
}
render() { ... }
}
withApollo(MyComponent);
出于好奇,对点击事件运行查询的目标是什么?也许有更好的方法来实现基本目标.
Out of curiosity, what's the goal of running a query on a click event? Perhaps there is a better way to accomplish the underlying goal.
这篇关于Apollo GraphQL React - 如何在点击时查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!