【问题标题】:GraphQL, React, Apollo - Expected Iterable, but did not find one for field "..."GraphQL、React、Apollo - 预期可迭代,但没有为字段“...”找到一个
【发布时间】:2020-07-04 11:07:31
【问题描述】:

我是一名正在从事个人项目的学生初学者。我正在尝试构建一个简单的 Web 应用程序,它从 API (https://docs.stratz.com/index.html) 请求英雄列表并在网页上显示他们的 ID 和显示名称。我已经成功地完成了与 SpaceX 发射类似的事情,但我似乎无法让它发挥作用。

在设置我的服务器并在本地端口上运行后,我收到一个错误“预期可迭代,但没有为字段 RootQueryType.Heroes 找到一个”。我很确定这是因为在我的架构中,我将 RootQuery 定义如下:

const HeroType = new GraphQLObjectType({
  name: 'Hero',
  fields: () => ({
    id: {type: GraphQLInt },
    displayName: {type: GraphQLString },
  })
});


// Root Query
const RootQuery = new GraphQLObjectType({
  name: 'RootQueryType',
  fields:{
    //list of heroes
    Heroes: {
      type: new GraphQLList(HeroType),
      // This is where we get data
      resolve(parent, args){
        return axios
          .get('https://api.stratz.com/api/v1/Hero')
          .then(res => res.data);
      }
    }
  },
});

我认为,由于我已将 Heroes 定义为 GraphQLList,因此我收到错误消息,因为我没有从服务器接收到可迭代或数组。在他们的文档中,他们的服务器返回如下示例:

{
  "additionalProp1": {
    "id": 0,
    "name": "string",
    "displayName": "string",
    "shortName": "string",
    "abilities": [
      {
        "heroId": 0,
        "gameVersionId": 0,
        "slot": 0,
        "abilityId": 0
      }
    ],
    "roles": [
      {
        "heroId": 0,
        "roleId": 0,
        "gameVersionId": 0,
        "level": 0
      }
    ],
    "talents": [
...
// the list goes on and on with all sorts of info

如果我错了,请纠正我,但我认为我的问题是我的 schema.js 文件没有处理他们示例中列出的“additionalProp1”。有人可以指出我纠正我的模式以处理这个问题的正确方向吗?

【问题讨论】:

    标签: javascript reactjs api graphql schema


    【解决方案1】:

    您点击的 API 似乎返回了一个对象,该对象是英雄对象的 map 英雄 ID。它看起来像这样:

    {
      "1": {
        "id": 1,
        "name": "npc_dota_hero_antimage",
        ...
      },
      "2": {
        "id": 2,
        "name": "npc_dota_hero_axe",
        ...
      },
      ...
    }
    

    我们想要的是这些对象的数组。一种方法是:

    .then(res => {
      const heroesById = res.data
      // get an array of the keys of the object
      const ids = Object.keys(heroesById) 
      // map over the array
      return ids.map(id => heroesById[id])
    });
    

    【讨论】:

      猜你喜欢
      • 2019-08-01
      • 2021-09-14
      • 2021-01-20
      • 2019-12-06
      • 2018-09-06
      • 2017-10-31
      • 2021-07-28
      相关资源
      最近更新 更多