【问题标题】:How to use client.query without JSX components in Apollo Client?如何在 Apollo Client 中使用没有 JSX 组件的 client.query?
【发布时间】:2024-01-29 06:30:01
【问题描述】:

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

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

有了这个,我正在寻找像

这样的对象
{
  "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;
}

有什么建议吗?

【问题讨论】:

  • 请发布您当前拥有的代码。 *.com/help/mcve 是代码问题所必需的。目前尚不清楚您的代码目前是什么样子,但很可能需要以任何方式使用组件,因为这就是 React 中事物的交互方式。
  • 请编辑您的问题并在其中格式化您的代码,而不是将其作为评论发送
  • 好的!我刚刚把我的代码
  • 这是一个非常奇怪的 gql 查询语法,这在 GQL 操场上有效吗?你能告诉我使用结果的 JSX 部分吗,我会告诉你如何使用 Query 节点,这很容易
  • 好的,我已经将代码更新为我正在做的真实方式。

标签: reactjs graphql apollo react-apollo apollo-client


【解决方案1】:

试试这个

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 来检索数据

【讨论】:

  • 谢谢拉希德!我用你的答案更新了代码,但现在 TypeScript 告诉我 withApollo 不希望收到作为参数的承诺
  • 错误是:'({ client }: { client: any; }) => Promise' 类型的参数不可分配给 'ComponentType>'。
  • @ClementeSerranoSutil 检查,我已经更新了答案。
  • @ClementeSerranoSutil 让我知道是否有帮助。如果你想在生命周期方法中添加你的逻辑,JSX 不会帮助你。您需要将 HOC 与 Apollo 一起使用。
  • 客户是什么?我正在使用Gatsby,它在构建时使用graphql,我认为它没有要查询的客户端,或者我认为客户端可能是本地的?
最近更新 更多