如何在 Apollo Client 中使用没有 JSX 组件的 client.query?

Cle*_*til 5 apollo reactjs graphql react-apollo apollo-client

我正在尝试使用 React 在 Apollo Client 中进行查询而不返回 JSX 组件,只是一个对象(data向 Apollo Server 进行常见查询时收到的对象)。

我尝试使用<Query />组件,但它返回一个 React 节点,我只需要一个对象。该文档仅解释了在某些时候返回 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);
Run Code Online (Sandbox Code Playgroud)

有了这个,我正在寻找一个像

{
  "data": {
    "myQuery": [
      {
        "attr1": "something 1...",
        "attr2": "another thing 1..."
      },
      {
        "attr1": "something 2...",
        "attr2": "another thing 2..."
      },
      {
        "attr1": "something 3...",
        "attr2": "another thing 3..."
      }
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)

但是我从浏览器收到的是

ƒ WithApollo(props) {
    var _this = _super.call(this, props) || this;

    _this.setWrappedInstance = _this.setWrappedInstance.bind(_this);
    return _this;
}
Run Code Online (Sandbox Code Playgroud)

有什么建议吗?

Rac*_*our 4

试试这个

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);
Run Code Online (Sandbox Code Playgroud)

您是通过控制台记录该函数而不是调用它来获取其结果您可能需要一些生命周期函数,例如componentDidMount检索数据