[英]GraphQL, React, Apollo - Expected Iterable, but did not find one for field "..."
我是一名從事個人項目的學生初學者。 我正在嘗試構建一個簡單的 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”。 有人能指出我正確的方向來糾正我的模式來處理這個問題嗎?
您正在使用的 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])
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.