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的引用传递给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);
出于好奇,对click事件运行查询的目的是什么?也许有更好的方法可以实现基本目标.
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屋!