You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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做非空/类型校验,只要入参不是数组就会直接崩溃。

修复步骤

  1. 调整接口请求地址:如果你的需求是拉取Rocketseat组织的公开仓库列表,把请求地址替换为https://api.github.com/orgs/rocketseat/repos,该接口返回的是仓库数组,符合遍历渲染的要求。
  2. 给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: [] }
    }
  }
}
  1. 给组件入参增加默认值,再加一层可选链校验,同时补充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}>&#10094;</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}>&#10095;</a>
      </div>
    </div>
  );
}

内容的提问来源于stack exchange,提问作者Gustavo Leterio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 10:09:02