如何将对象中的数据提取到 Apollo Query 组件中
How to extract data from an object, into Apollo Query component
正在尝试从 graphql 中提取数据 API 但无法使用 map()
,因为数据作为对象返回。
不过,我在 Apollo 服务器上得到了想要的结果(基于我的架构)。
这是我执行代码后得到的结果:
data.getRandomMeal.map is not a function
调试时显示data = { getRandomMeal {...} }
<Query
query={
gql`{
getRandomMeal {
idMeal
strMeal
}
}`
}
>
{({ data }) => {
if (data === undefined) return null;
return (
<ul>
{data.getRandomMeal && data.getRandomMeal.map(meal => (
<li key={meal.idMeal}>{meal.strMeal} </li>
))}
</ul>
);
}}
</Query>
const typeDefs = gql`
type Meal{
idMeal: ID
strMeal: String
strTags: String
strCategory: String
}
type Query {
getRandomMeal: Meal
}
`;
const resolvers = {
Query: {
getRandomMeal: async (_, __, { dataSources }) =>
dataSources.RandomRecipe.getRandomMeal()
}
};
数据源:
class RandomRecipe extends RESTDataSource{
constructor() {
super();
this.baseURL = 'https://www.themealdb.com/api/json/v1/1/random.php';
}
async getRandomMeal(){
const meal = await this.get('/');
return meal.meals[0];
}
};
module.exports = RandomRecipe;
const meal = await this.get('/');
与
有关
this.baseURL = 'https://www.themealdb.com/api/json/v1/1/random.php';
结果不正确 URL
'https://www.themealdb.com/api/json/v1/1/random.php/'
在
中使用空字符串应该就足够了
const meal = await this.get('');
response可以直接使用,不用map:
{({ data }) => {
if (data === undefined) return null;
const meal = data.getRandomMeal;
return (
<ul>
{meal && (
<li key={meal.idMeal}>{meal.strMeal} </li>
)}
</ul>
);
}}
正在尝试从 graphql 中提取数据 API 但无法使用 map()
,因为数据作为对象返回。
不过,我在 Apollo 服务器上得到了想要的结果(基于我的架构)。
这是我执行代码后得到的结果:
data.getRandomMeal.map is not a function
调试时显示data = { getRandomMeal {...} }
<Query
query={
gql`{
getRandomMeal {
idMeal
strMeal
}
}`
}
>
{({ data }) => {
if (data === undefined) return null;
return (
<ul>
{data.getRandomMeal && data.getRandomMeal.map(meal => (
<li key={meal.idMeal}>{meal.strMeal} </li>
))}
</ul>
);
}}
</Query>
const typeDefs = gql`
type Meal{
idMeal: ID
strMeal: String
strTags: String
strCategory: String
}
type Query {
getRandomMeal: Meal
}
`;
const resolvers = {
Query: {
getRandomMeal: async (_, __, { dataSources }) =>
dataSources.RandomRecipe.getRandomMeal()
}
};
数据源:
class RandomRecipe extends RESTDataSource{
constructor() {
super();
this.baseURL = 'https://www.themealdb.com/api/json/v1/1/random.php';
}
async getRandomMeal(){
const meal = await this.get('/');
return meal.meals[0];
}
};
module.exports = RandomRecipe;
const meal = await this.get('/');
与
有关this.baseURL = 'https://www.themealdb.com/api/json/v1/1/random.php';
结果不正确 URL
'https://www.themealdb.com/api/json/v1/1/random.php/'
在
中使用空字符串应该就足够了const meal = await this.get('');
response可以直接使用,不用map:
{({ data }) => {
if (data === undefined) return null;
const meal = data.getRandomMeal;
return (
<ul>
{meal && (
<li key={meal.idMeal}>{meal.strMeal} </li>
)}
</ul>
);
}}