【问题标题】:JS TypeError: Cannot Read Property "..." of Undefined, Despite DATA being returned?JS TypeError:无法读取未定义的属性“...”,尽管返回了数据?
【发布时间】:2020-02-24 08:25:36
【问题描述】:

我正在关注这个 Apollo 分页教程:

Apollo Pagination Examples

我的问题总结:

我有一个在操场上工作的已知工作 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


【解决方案1】:

在从服务器或缓存中获取数据之前,data 属性将是未定义的。为防止出现错误,请避免在加载完成之前对data 进行解构,或者在适当的情况下提供默认值:

const {
  data: {
    errorlogsConnection: errorLogs
  } = {},
  loading,
  fetchMore,
  error,
} = useQuery(ERROR_LOG_PAGINATION)

【讨论】:

  • 这确实有点帮助,它会在等待响应时触发“加载”元素显示,但现在我得到了我认为的无限循环。它冻结了浏览器,所以肯定还有其他东西。
猜你喜欢
  • 1970-01-01
  • 2019-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-02
  • 2023-03-19
  • 1970-01-01
相关资源
最近更新 更多