如何在 Apollo Client 中使用没有 JSX 组件的 client.query? [英] How to use client.query without JSX components in Apollo Client?

查看:24
本文介绍了如何在 Apollo Client 中使用没有 JSX 组件的 client.query?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 React 在 Apollo Client 中进行查询而不返回 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆