如何在Apollo Client中使用没有JSX组件的client.query? [英] How to use client.query without JSX components in Apollo Client?
问题描述
我正在尝试使用React在Apollo客户端中进行查询,而不返回一个JSX组件,而只是一个对象(对Apollo Server进行通用查询时会收到的data
对象).
I'm trying to make a query in Apollo Client with React without returning a JSX component, just an object (the data
object that is received when making a common query to Apollo Server).
我尝试使用<Query />
组件,但是它返回了我一个React Node,我只需要一个对象.当我要做的只是发送请求并在回调中处理响应时,文档仅说明在某些时候返回JSX组件的方法.
I tried using <Query />
component, but it returns me a React Node and I only need an object. The documentation only explain methods that return JSX components at some point, when all that I'm looking to do is send a request and process the response in a callback.
实际上我正在尝试这种方式(我在React中使用TypeScript):
Actually I'm trying this way (I'm using TypeScript in React):
import React from 'react';
import { withApollo } from 'react-apollo';
import gql from 'graphql-tag';
const MY_QUERY = gql`
query MY_QUERY {
myQuery {
attr1
attr2
}
}
`;
const res = ({ client }: { client: any }) =>
client
.query(MY_QUERY)
.then((data: { data: any }) => data);
withApollo(res);
console.log(res);
有了这个,我正在寻找的是像
With this, what I'm looking is for a object like
{
"data": {
"myQuery": [
{
"attr1": "something 1...",
"attr2": "another thing 1..."
},
{
"attr1": "something 2...",
"attr2": "another thing 2..."
},
{
"attr1": "something 3...",
"attr2": "another thing 3..."
}
]
}
}
但是我从浏览器收到的是
But what I'm receiving from the browser is
ƒ WithApollo(props) {
var _this = _super.call(this, props) || this;
_this.setWrappedInstance = _this.setWrappedInstance.bind(_this);
return _this;
}
有什么建议吗?
推荐答案
尝试使用此方法
class anyComponent extends React.Component<Props> {
state = {
results: null,
}
componentDidMount = async () => {
const {client} = this.props;
res = await client.query({query: MY_QUERY});
console.log(res);
this.setState({results: res})
}
render() {
// check if any results exist (just an example)
return results ? <AnyJsx results={results}/> : null;
}
}
export default withApollo(anyComponent);
您在控制台上记录了该函数,而不是调用它来获取其结果
您可能需要一些生命周期功能,例如componentDidMount
来检索数据
You were console logging the function instead of calling it to get its result
You may need some lifecycle functions like componentDidMount
to retrieve data
这篇关于如何在Apollo Client中使用没有JSX组件的client.query?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!