NextJS项目构建预渲染报错:Cannot read properties of undefined (reading 'city')
解决Next.js构建时预渲染NotFound页面的TypeError错误
错误原因分析
构建时报错TypeError: Cannot read properties of undefined (reading 'city'),根源有两个:
- 独立路由的NotFound页面缺少数据逻辑:你创建了
/[country]/NotFound.tsx这个独立路由页面,但该页面没有配置getServerSideProps或getStaticProps来获取country和city参数,预渲染时props为undefined,导致读取props.city失败。 - 组件参数传递与解构不匹配:在
City.tsx中调用<NotFound props={props} />时,传递了完整的props对象,但NotFound组件的解构方式{ props }会导致你实际要访问的city需要写成props.props.city,不符合预期逻辑。
解决方案
方案1:移除独立的NotFound路由(推荐)
既然你已经在City.tsx中通过状态判断渲染NotFound组件,完全不需要保留/[country]/NotFound.tsx这个独立页面。直接删除该文件,即可消除预渲染该页面的错误。
方案2:修复NotFound组件的参数处理
如果需要保留独立的NotFound路由,按以下步骤修改:
1. 调整NotFound组件的参数接收
修改NotFound.tsx,直接解构需要的city参数,并添加默认值防止undefined:
import React from "react"; import SearchForm from "../../components/Essential/SearchForm"; function NotFound({ city }) { // 给city设置默认值,避免undefined报错 const targetCity = city || "该城市"; return ( <div className="container-lg mx-auto"> <div className="my-8 mt-20"> <SearchForm /> <span className="text-xs text-gray-400"> {targetCity} 不在数据库中。 <em className="ml-1 text-white underline cursor-pointer"></em> </span> </div> </div> ); } // 添加数据获取逻辑,确保预渲染时能拿到city参数 export async function getServerSideProps(ctx) { const { country, city } = ctx.query; return { props: { country, city, }, }; } export default NotFound;
2. 修正City.tsx中调用NotFound的方式
在City.tsx中,直接传递city参数给NotFound组件:
// 原代码:<NotFound props={props} /> // 修改为: <NotFound city={city} />
额外优化建议
- 在
City.tsx的useEffect依赖数组中添加country和city,确保参数变化时重新请求数据:useEffect(() => { // ... 原有请求逻辑 }, [country, city]); // 添加依赖 - 给
City组件的props添加TypeScript类型定义,避免隐式any类型:interface CityProps { country: string; city: string; } const City = ({ country, city }: CityProps) => { // ... 组件逻辑 }
内容的提问来源于stack exchange,提问作者JohnJonta
相关产品推荐
相关产品推荐

