我尝试使用 React 在 Apollo 客户端中进行查询,而不返回 JSX 组件,仅返回一个对象(对 Apollo 服务器进行常见查询时收到的 data
对象)。
我尝试使用<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
来检索数据
关于reactjs - 如何在 Apollo 客户端中使用没有 JSX 组件的 client.query?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54620761/