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

Next 13使用getStaticProps时map报错:Cannot read properties of undefined

问题原因及解决方法

核心问题1:客户端组件无法使用getStaticProps

你给组件添加了"use client"指令,这会将组件标记为客户端组件,但getStaticProps是仅支持服务器组件的静态生成方法——客户端组件不会执行这个函数,所以posts参数根本没有被赋值,自然为undefined,调用map时就会触发报错。

核心问题2:GitHub API请求地址无效

代码里的请求URL是https://api.github.com/users/{myuser}/repos,其中{myuser}是占位符,需要替换成你实际的GitHub用户名(比如https://api.github.com/users/octocat/repos),否则请求会返回404错误,拿到的posts不是预期的数组。

修复后的完整代码

import { GetStaticProps } from "next";

interface PostGithubProps {
  posts: {
    name: string
  }[]
}

export default function Github({ posts = [] }: PostGithubProps) {
  return(
    <>
     {posts.map(post => (
       <p key={post.name}>{post.name}</p>
      ))}
    </>
  )
}

export const getStaticProps: GetStaticProps = async () => {
  // 替换为你的实际GitHub用户名
  const username = "your-github-username";
  const res = await fetch(`https://api.github.com/users/${username}/repos`)
  
  // 处理请求失败的情况,避免错误数据导致组件崩溃
  if (!res.ok) {
    return {
      props: {
        posts: []
      }
    }
  }
  
  const posts = await res.json()

  return { 
    props: {
      posts
    }
  }
} 

额外优化说明

  • 给posts参数设置默认值[],即使请求失败或数据未正常加载,也不会触发map的报错。
  • 增加res.ok判断,处理API请求失败的场景,保证组件能稳定渲染。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 22:29:53