Vercel部署Next.js项目getStaticPaths报authors.map is not a function错误求解
结论先行
不需要将函数组件改写为类组件,该报错和组件类型无关。
错误根因
报错TypeError: authors.map is not a function的核心原因是getStaticPaths中请求接口拿到的authors不是数组类型,无法调用数组的map方法。
修复方案
1. 适配Strapi接口返回结构
如果你使用的是Strapi v4及以上版本,列表接口默认不会直接返回内容数组,而是包裹了data、meta字段的对象,结构如下:
{ "data": [/* 实际的作者数组在这里 */], "meta": {/* 分页等元信息 */} }
你需要修改取值逻辑,同时加兜底兼容异常情况:
export async function getStaticPaths() { const response = await fetch(`${process.env.NEXT_PUBLIC_STRAPI_API_URL}/authors`); const resData = await response.json(); // 优先取data字段,兜底空数组避免map调用报错 const authors = resData.data || []; return { paths: authors.map((author) => ({ params: { // Strapi v4的业务字段存在attributes属性下,兼容v3/v4两种格式 username: author.username ?? author.attributes?.username } })), fallback: 'blocking' } }
2. 同步修复getStaticProps的兼容逻辑
同理,查询单个作者的接口返回结构也需要适配,同时加兜底避免后续渲染报错:
export async function getStaticProps({ params }) { const response = await fetch( `${process.env.NEXT_PUBLIC_STRAPI_API_URL}/authors?username=${params.username}` ); const resData = await response.json(); const authors = resData.data || resData || []; return { props: { author: authors[0] || {} }, revalidate: 10 } }
3. 组件层加异常兼容
给组件入参加默认值,业务字段取值用可选链,避免字段缺失时渲染崩溃:
// 入参加默认空对象 const Author = ({ author = {} }) => { // 无有效作者信息时返回降级提示 if (!author.id && !author.attributes?.id) return <div>该作者不存在</div> const authorInfo = author.attributes || author; return ( <div className="author-page"> <img src={`https://pacific-sands-66227.herokuapp.com/uploads${authorInfo.photo?.url}`} alt={authorInfo.name} /> <div className="author-details"> <h1>{authorInfo.name}</h1> <p className="bio">{authorInfo.bio}</p> <p>@{authorInfo.twitter} - {authorInfo.website}</p> </div> </div> ); };
4. 检查Vercel环境变量
确认Vercel项目后台已经正确配置了NEXT_PUBLIC_STRAPI_API_URL环境变量,且值为可公网访问的Strapi服务地址,避免请求错误导致返回非预期格式的内容。
内容的提问来源于stack exchange,提问作者DNH
相关产品推荐
相关产品推荐

