Next.js拉取GitHub接口报Cannot read property 'map' of undefined求助
问题原因&解决方案
核心错误原因
你遇到的typeError: Cannot read property 'map' of undefined由两个问题共同导致:
- 调用的接口返回值类型不符合预期:你请求的
https://api.github.com/orgs/rocketseat是单组织查询接口,返回值为单个对象,而map是数组专属方法,调用对象的map方法自然会抛出错误。 - 代码缺少容错兜底逻辑:没有对入参
mods做非空/类型校验,只要入参不是数组就会直接崩溃。
修复步骤
- 调整接口请求地址:如果你的需求是拉取Rocketseat组织的公开仓库列表,把请求地址替换为
https://api.github.com/orgs/rocketseat/repos,该接口返回的是仓库数组,符合遍历渲染的要求。 - 给
getStaticProps增加错误处理,避免接口请求失败时返回异常数据:
export const getStaticProps = async () => { try { const response = await fetch('https://api.github.com/orgs/rocketseat/repos'); if (!response.ok) throw new Error('接口请求失败') const data = await response.json(); return { props: { mods: data } } } catch (e) { // 请求失败时返回空数组兜底 return { props: { mods: [] } } } }
- 给组件入参增加默认值,再加一层可选链校验,同时补充map遍历必填的key属性避免控制台警告:
// 解构时给mods默认空数组 const ProjectLines = ({ mods = [] }) => { return ( <div className={styles.categoryWrapper}> <h4 className={styles.subTitle}>Escritório</h4> <div className={styles.lineWrapper}> <a className={styles.leftArrow}>❮</a> <div className={styles.line}> {/* 加可选链再兜底一次,极端情况也不会报错 */} {mods?.map(mod => ( <div className={styles.imageBox} key={mod.id}> <Image src={photo} width={400} height={200} layout="responsive" lazy="true" placeholder="blur" /> <div className={styles.linkContent}> <span className={styles.name}>{mod.name}</span> <Link href=""><a className={styles.link}>Veja Mais!</a></Link> </div> </div> ))} </div> <a className={styles.rightArrow}>❯</a> </div> </div> ); }
内容的提问来源于stack exchange,提问作者Gustavo Leterio
相关产品推荐
相关产品推荐

