GraphQL+Next.js+TypeScript项目映射GitHub Showcase仓库数据报错求助
问题根源与解决方案
核心报错原因是类型定义冗余嵌套,导致数据取值路径多写了一层itemShowcase:
你在GraphQL查询中返回的viewer.itemShowcase已经是直接包含items字段的对象,但你定义的itemShowCaseProps多嵌套了一层itemShowcase字段,导致取值时额外访问了不存在的属性,触发undefined报错。
修正步骤
1. 修正冗余的类型定义
// 原itemShowCaseProps去掉多余的嵌套层 export type ItemShowCaseProps = { items: { nodes: Array<{ name: string description: string url: string }> } } export type QueryProps = { following: FollowingProps followers: FollowersProps repositories: RepositoriesProps // 直接关联修正后的ItemShowCaseProps itemShowcase: ItemShowCaseProps }
2. 修正组件取值路径,添加空值防御
同时注意不要写错nodes属性(你报错信息中出现的items.node属于笔误,需要修正为items.nodes),添加可选链和空数组兜底避免边缘情况报错:
<S.CardWrapper> {itemShowcase?.items?.nodes?.map((repo, index) => ( <CardComponent key={index} url={repo.url} name={repo.name} description={repo.description} /> )) ?? []} </S.CardWrapper>
内容的提问来源于stack exchange,提问作者Rafael Dell'Aquila
相关产品推荐
相关产品推荐

