Javascript GraphQL、React、Apollo-预期为Iterable,但未为field找到一个&引用;
我是一个初学者,正在做一个个人项目。我试图构建一个简单的web应用程序,从API()请求英雄列表,并在网页上显示他们的ID和displayname。我已经成功地完成了类似的SpaceX发射,但我似乎无法让它工作 在设置服务器并在本地端口上运行后,我得到一个错误“预期Iterable,但没有为字段RootQueryType.Heroes找到一个”。我很确定这是因为在我的模式中,我定义了如下RootQuery:Javascript GraphQL、React、Apollo-预期为Iterable,但未为field找到一个&引用;,javascript,reactjs,api,graphql,schema,Javascript,Reactjs,Api,Graphql,Schema,我是一个初学者,正在做一个个人项目。我试图构建一个简单的web应用程序,从API()请求英雄列表,并在网页上显示他们的ID和displayname。我已经成功地完成了类似的SpaceX发射,但我似乎无法让它工作 在设置服务器并在本地端口上运行后,我得到一个错误“预期Iterable,但没有为字段RootQueryType.Heroes找到一个”。我很确定这是因为在我的模式中,我定义了如下RootQuery: const HeroType = new GraphQLObjectType({ n
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定义为GraphQList
,因此我得到了一个错误,因为我没有从服务器接收回iterable或数组。在他们的文档中,他们的服务器返回如下示例:
{
"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”。有人能给我指出正确的方向来纠正我的模式来处理这个问题吗 您正在使用的API似乎将一个作为英雄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])
});