reactjs - 如何在 Apollo 客户端中使用没有 JSX 组件的 client.query?

标签 reactjs graphql apollo react-apollo apollo-client

我尝试使用 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/

相关文章:

javascript - ComponentDidMount 之外的状态似乎没有更新

reactjs - 禁用/解决方法 React 关键要求?

graphql - Sequelize组合在单个领域有很多关联

reactjs - Apollo - React (Typescript) 构建生产构建时的不变错误

node.js - `Extensions` 字段未显示在 apollo graphql 响应数据中

javascript - 如何使用 ref 访问当前节点

node.js - Express 覆盖react-router 客户端路由

GraphQL 中继突变配置 RANGE_ADD 的连接父名称

GraphQL:无法读取 Apollo 客户端中的响应 header

graphql - Apollo+GraphQL - 启发式片段手动匹配