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

Next.js执行npm run build构建预渲染页面报Cannot read 'map'错误如何解决?

错误根因

你的报错核心是Next.js执行预渲染时,/componentList/trending 页面的 trend 属性为 undefined,调用 map 方法时报错,具体有3个直接原因:

  • Next.js会自动将pages目录下的所有JS文件识别为路由页面,你把公共组件trending.js放在了pages/componentList/目录下,构建时Next.js会将其作为独立路由页面预渲染,但你没有给这个页面配置getServerSideProps传入trend参数,导致预渲染时props.trend为空。
  • 接口请求没有做异常兜底,即使是首页的getServerSideProps,如果接口返回数据结构不符合预期、trendingApi.sections.trending不存在,也会导致传递给组件的trend为undefined。
  • 你提供的Axios请求写法有误,无法正常发起请求拿到返回数据。

修复方案

1. 修复组件存放位置

将pages/componentList/trending.js移动到项目根目录的components/文件夹下(如果没有就新建这个目录),避免Next.js将其识别为独立路由页面。之后修改首页的引入路径:

// pages/index.js 中修改引入路径
import Trending from '../components/trending';

2. 增加空值兜底判断

两处修改避免空值报错:

  • 首页getServerSideProps中给trend加默认空数组:
// pages/index.js 中修改
const trend = trendingApi?.sections?.trending || [];
  • Trending组件中给props加默认值,或者调用map时用可选链:
// 写法1:组件参数加默认值
function Trending({ trend = [] }) {
  // 原有逻辑
}

// 写法2:调用map时加可选链
{props.trend?.map((x,i) => (
  // 原有渲染逻辑
))}

3. 修正Axios请求写法

Axios的post方法第二个参数直接传入请求体对象,请求头放在第三个配置参数中,修正后写法:

const trending = await axios.post('https://lat.epapp.ae/api/v5/web/home',
  { title: "React POST Request Example" },
  { headers: { "Content-Type": "application/json" } }
)

修改完成后重新执行npm run build即可正常构建。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 16:36:06