React / Apollo:显示 GraphQL 查询的结果(useQuery hook)
React / Apollo: Displaying result of GraphQL query (useQuery hook)
我是 react/graphql/apollo 的新手,但是我已经遵循了关于如何在 www.apollographql.com 上使用 Apollo 进行 graphql 查询的指南。但是我好像无法显示结果。
这是我执行查询的代码
import React from "react";
import { useQuery } from 'react-apollo';
import gql from "graphql-tag";
const GET_PRODUCTS = gql`
query getProducts{
products(first: 1) {
edges {
node {
id
name
}
}
}
}
`;
const StartPage = () => {
const { loading, error, returnData } = useQuery(GET_PRODUCTS, {
variables: {},
});
return (
<p>Hello world, this should be the data: {returnData}</p>
);
};
我只看到“Hello world, this should be the data:”但是没有打印returnData?
我不能打印整个回复吗?
当我重新加载页面时,我可以在网络选项卡中清楚地看到我的查询
确实被执行了,我得到了正确的回应
要求
{"operationName":"getProducts","variables":{},"query":"query getProducts {\n products(first: 1) {\n edges {\n node {\n id\n name\n __typename\n }\n __typename\n }\n __typename\n }\n}\n"}
回应
{"data":{"products":{"edges":[{"node":{"id":"UHJvZHVjdDo3Mg==","name":"Apple Juice","__typename":"Product"},"__typename":"ProductCountableEdge"}],"__typename":"ProductCountableConnection"}}}
那么有没有人知道为什么 returnData 没有打印出来/为空?
应该是const { loading, error, data } = useQuery(GET_PRODUCTS, ...);
注意:data
不是returnData
。
当你解构对象时,你需要在涉及到键时准确无误。如果您需要 数据保存在一个名为 returnData
的变量中,您可以这样做:
const { loading, error, data: returnData } = useQuery(GET_PRODUCTS, {
variables: {},
});
另请注意,在 React 中,您不能只渲染花括号内的对象,React 需要字符串或数字。为了快速调试,您可以添加
return (
<p>Hello world, this should be the data: {JSON.stringify(returnData)}</p
);
否则,您应该显示 return 对象内部深处的数据。
我是 react/graphql/apollo 的新手,但是我已经遵循了关于如何在 www.apollographql.com 上使用 Apollo 进行 graphql 查询的指南。但是我好像无法显示结果。
这是我执行查询的代码
import React from "react";
import { useQuery } from 'react-apollo';
import gql from "graphql-tag";
const GET_PRODUCTS = gql`
query getProducts{
products(first: 1) {
edges {
node {
id
name
}
}
}
}
`;
const StartPage = () => {
const { loading, error, returnData } = useQuery(GET_PRODUCTS, {
variables: {},
});
return (
<p>Hello world, this should be the data: {returnData}</p>
);
};
我只看到“Hello world, this should be the data:”但是没有打印returnData? 我不能打印整个回复吗?
当我重新加载页面时,我可以在网络选项卡中清楚地看到我的查询 确实被执行了,我得到了正确的回应
要求
{"operationName":"getProducts","variables":{},"query":"query getProducts {\n products(first: 1) {\n edges {\n node {\n id\n name\n __typename\n }\n __typename\n }\n __typename\n }\n}\n"}
回应
{"data":{"products":{"edges":[{"node":{"id":"UHJvZHVjdDo3Mg==","name":"Apple Juice","__typename":"Product"},"__typename":"ProductCountableEdge"}],"__typename":"ProductCountableConnection"}}}
那么有没有人知道为什么 returnData 没有打印出来/为空?
应该是const { loading, error, data } = useQuery(GET_PRODUCTS, ...);
注意:data
不是returnData
。
当你解构对象时,你需要在涉及到键时准确无误。如果您需要 数据保存在一个名为 returnData
的变量中,您可以这样做:
const { loading, error, data: returnData } = useQuery(GET_PRODUCTS, {
variables: {},
});
另请注意,在 React 中,您不能只渲染花括号内的对象,React 需要字符串或数字。为了快速调试,您可以添加
return (
<p>Hello world, this should be the data: {JSON.stringify(returnData)}</p
);
否则,您应该显示 return 对象内部深处的数据。