Next.js问题:如何在组件中调用动态路由内容并解决空值报错?
问题
我按照教程实现了基于Next.js和WPGraphQL的无头WordPress应用,已通过[uri].js实现动态路由,可直接访问http://localhost:3000/opening2。现在我想在Featured.js组件中调用该路由对应的文章内容,代码如下:
export default function Featured(post) { return ( <div><Link href={post.uri} className="card"> <a className="card"> <h3>{post.title} →</h3> </a> </Link> </div> ) }
但访问http://localhost/featured时出现报错:
TypeError: Cannot read properties of null (reading 'title')
请问该如何修复这个错误?
解决方案
这个错误的核心是post参数为null或未正确传入,导致无法读取title属性,可从以下几个方向修复:
确认
post数据是否正确传入组件
检查调用Featured组件的父组件,是否传递了有效的post对象。比如父组件需确保通过WPGraphQL获取到文章数据后,再将其传入Featured:// 父组件示例 import Featured from './Featured'; export default function ParentComponent({ postData }) { if (!postData) return <div>加载中...</div>; return <Featured post={postData} />; }在
Featured组件中增加空值校验
直接在组件内部对post做判断,避免数据为空时崩溃:export default function Featured(post) { const { title = '暂无标题', uri = '#' } = post || {}; return ( <div> <Link href={uri} className="card"> <a className="card"> <h3>{title} →</h3> </a> </Link> </div> ) }也可用可选链操作符简化:
export default function Featured(post) { return ( <div> <Link href={post?.uri || '#'} className="card"> <a className="card"> <h3>{post?.title || '暂无标题'} →</h3> </a> </Link> </div> ) }检查动态路由
[uri].js的数据获取逻辑
如果Featured在动态路由页面中使用,要确保getStaticProps或getServerSideProps正确获取对应uri的文章数据,并传递给组件:// [uri].js中的数据获取示例 export async function getStaticProps({ params }) { const { uri } = params; const res = await fetch('你的WPGraphQL接口地址', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ query: ` query GetPostByUri($uri: String!) { postBy(uri: $uri) { title uri } } `, variables: { uri } }) }); const data = await res.json(); if (!data.data.postBy) { return { notFound: true }; } return { props: { post: data.data.postBy } }; }
内容的提问来源于stack exchange,提问作者bandungeuy
相关产品推荐
相关产品推荐

