【发布时间】:2020-02-24 08:25:36
【问题描述】:
我正在关注这个 Apollo 分页教程:
我的问题总结:
我有一个在操场上工作的已知工作 GraphQL 查询。当我尝试获取数据并在 React 组件中使用它时,如上面的 Apollo 链接中所述,我收到以下错误:
“TypeError:无法读取未定义的属性'errorlogsConnection'”
但是,当我在 Web 控制台中检查来自 graphQL api 的响应时,查询确实实际上返回了数据。附上图片。
我相信我可能试图错误地引用该对象,但我无法发现我的错误是什么。
注意:我已经能够在同一个项目的其他 React 组件中查询和使用同一个 API 端点而没有问题。
这里是涉及的代码:
我正在使用这个查询,它在我的 GraphiQL 操场上工作:
query errorlogsConnection($cursor: String) {
errorlogsConnection(orderBy: errorid_DESC, first: 4, after: $cursor) {
edges {
node {
errorid
errorlog
entrydate
}
}
pageInfo {
hasPreviousPage
hasNextPage
endCursor
startCursor
}
}
}
这是我根据他们的教程改编的 ReactJS 代码:
function ErrorLogsPagination() {
const {data: {errorlogsConnection: errorLogs}, loading, fetchMore, error} = useQuery(
ERROR_LOG_PAGINATION
);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error :(</p>;
return (
<ErrorLogs
entries={errorLogs || []}
onLoadMore={() =>
fetchMore({
variables: {
cursor: errorLogs.pageInfo.endCursor
},
updateQuery: (previousResult, { fetchMoreResult }) => {
const newEdges = fetchMoreResult.errorLogs.edges;
const pageInfo = fetchMoreResult.errorLogs.pageInfo;
return newEdges.length
? {
// Put the new comments at the end of the list and update `pageInfo`
// so we have the new `endCursor` and `hasNextPage` values
comments: {
__typename: previousResult.errorLogs.__typename,
edges: [...previousResult.errorLogs.edges, ...newEdges],
pageInfo
}
}
: previousResult;
}
})
}
/>
);
}
【问题讨论】:
-
嗯,你通常能够直接解构异步的东西吗?我不知道 GraphQL,但您的问题是尝试访问尚未获取/完成的异步操作的数据时常见的问题。它可能会在结果返回之前尝试解构。
-
我相信你是对的。 Daniel Rarden 的回答有助于将这个问题推得更远。示例代码似乎不是这类事情的最佳实践,所以我正在研究等待数据的正确方法。
标签: reactjs graphql react-apollo