【发布时间】:2020-02-17 00:35:39
【问题描述】:
所以我需要一双新鲜的眼睛来帮助我!我刚开始使用新的阿波罗钩子,它们非常酷!但是,当我尝试传递变量时遇到了一个问题,它返回未定义。
我在 graphql 服务器中有这个查询,它访问了一个休息 API,但目前我只返回标量 JSON
fetchRecipes(calories: String!, meal: String!): JSON
在我的组件中:
const { data, loading, error } = useQuery(FETCH_RECIPES, {
variables: { calories: 500, meal: "beef" }
});
const FETCH_RECIPES = gql`
query FetchRecipes($calories: String, $meal: String) {
fetchRecipes(calories: $calories, meal: $meal)
}
`;
当我console.log(data) 它返回undefined,
但是,为什么会这样呢? (不通过useQuery传递变量)
query {
fetchRecipes(calories: "500", meal: "beef")
}
这是组件的样子:
const Recipes = () => {
const { data, loading, error } = useQuery(FETCH_RECIPES, {
variables: { calories: "500", meal: "beef" }
});
if (loading) return <Loading>Loading...</Loading>;
if (error) return <Error>Data couldn't be fetched</Error>;
return (
<RecipeContext.Consumer>
{({ suggestedCaloricIntake }) => (
<View>
<Text>Suggested: {suggestedCaloricIntake}</Text>
<Picture
style={{ width: 150, height: 150 }}
source={{ uri: data.fetchRecipes.hits[0].recipe.image }}
accessibilityLabel='meal image'
/>
</View>
)}
</RecipeContext.Consumer>
);
};
【问题讨论】:
-
你做日志的时候异步功能已经完成了吗?
-
@Markus 感谢您的回复 :)!是的,我更新了问题以包含组件的代码。它遇到错误条件并返回一般错误消息。当我将变量直接硬编码到查询中时,它会返回一些数据
-
卡路里应该是一个字符串
-
@DanielRearden 抱歉,这是 stackoverflow 上的错字,我在编辑器中将其作为字符串
-
我还注意到,字符串类型在模板化的 const Query 中没有! (非空),但在您的架构中它与!。查看 apollo 文档,在他们的示例中两者都匹配。也许这会有所作为?
标签: graphql apollo react-apollo apollo-client