我正在尝试使用 React 在 Apollo 客户端中进行查询,而不返回 JSX 组件,只是一个对象(data
对 Apollo 服务器进行公共查询时收到的对象)。
我尝试使用<Query />
组件,但它返回给我一个 React Node,我只需要一个对象。该文档仅解释在某个时刻返回 JSX 组件的方法,而我要做的只是发送请求并在回调中处理响应。
实际上我正在尝试这种方式(我在 React 中使用 TypeScript):
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);
有了这个,我正在寻找像这样的对象
{
"data": {
"myQuery": [
{
"attr1": "something 1...",
"attr2": "another thing 1..."
},
{
"attr1": "something 2...",
"attr2": "another thing 2..."
},
{
"attr1": "something 3...",
"attr2": "another thing 3..."
}
]
}
}
但我从浏览器收到的是
ƒ 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
检索数据
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)