Next.js博客报错Cannot read properties of undefined (reading 'author')
问题现象
访问动态路由文章详情页localhost:3000/post/react-tesing时,程序抛出错误:TypeError: Cannot read properties of undefined (reading 'author')
报错原因
- 动态路由页面
[slug].js缺失Next.js必需的数据预获取逻辑,页面组件接收不到post属性,初始渲染时post值为undefined,直接读取post.author就会触发类型错误 - 存在拼写错误风险:访问路径里的
react-tesing疑似拼写错误(正确应为react-testing),会导致接口查询不到对应文章,返回空值;GraphQL查询里的封面字段写为featuredimage,和项目默认的驼峰字段featuredImage不匹配,会导致接口返回异常 - 组件未做加载态兜底,接口请求完成前直接操作
post的属性会触发报错
修复方案
- 在
[slug].js文件中补充Next.js动态路由所需的数据获取方法,将接口返回的文章数据作为props传入页面组件,在文件中组件定义后、导出前添加以下代码:
export async function getStaticPaths() { const posts = await getPosts(); return { paths: posts.map((post) => ({ params: { slug: post.slug } })), fallback: false, }; } export async function getStaticProps({ params }) { const post = await getPostDetails(params.slug); return { props: { post }, }; }
- 给页面组件增加空值兜底逻辑,避免数据加载完成前访问空值属性触发报错,修改组件开头逻辑:
const PostDetails = ({post}) => { // 数据未返回时展示加载提示 if (!post) { return <div className="container mx-auto px-10 py-16 text-center">文章加载中...</div> } return ( <div className='container mx-auto px-10 mb-8'> <div className="grid grid-cols-1 lg:grid-cols-12 gap-12"> <div className='col-span-1 lg:col-span-8'> <PostDetail post={post} /> <Author author={post.author} /> <CommentsForm slug={post.slug} /> <Comments slug={post.slug}/> </div> <div className='col-span-1 lg:col-span-4'> <div className='relative lg:sticky top-8'> <PostWidget slug={post.slug} categories={post.categories.map((category) => category.slug)}/> <Categories /> </div> </div> </div> </div> ); };
- 修正拼写问题
- 确认访问的文章slug和CMS后台存储的slug完全一致,修正路径里的拼写错误
- 核对GraphQL查询的字段名和CMS schema一致,将
featuredimage修改为正确的featuredImage,保证接口能正常返回全量文章数据
内容的提问来源于stack exchange,提问作者claudiaaaa
相关产品推荐
相关产品推荐

