NextJS+Sanity博客部署/构建报错:无法解构undefined的post的title
问题
使用NextJS + Sanity开发博客,本地开发模式运行完全正常,但在Vercel部署或VSCode构建时出现以下错误:
info - Generating static pages (0/8)TypeError: Cannot destructure property 'title' of 'post' as it is undefined.
组件代码概览:
export default function SinglePost({ post }) { const { title, imageUrl, publishedAt, description, topics, rescources, sourcecode, body = [], } = post; return( <div> <h1>{title}</h1> //remaining code.... </div>) } const query = groq`*[_type == "post" && slug.current == $slug][0]{ "title": title, "imageUrl": mainImage.asset->url, description, "topics": topics[], "rescources": rescources[], "sourcecode": sourcecode, "publishedAt": publishedAt, body, }`; export async function getStaticPaths() { const paths = await client.fetch( `*[_type == "post" && defined(slug.current)][].slug.current` ); return { paths: paths.map((slug) => ({ params: { slug } })), fallback: true, }; } export async function getStaticProps(context) { const { slug = "" } = context.params; const post = await client.fetch(query, { slug }); return { props: { post, }, }; }
解决方案
核心原因
因为你设置了fallback: true,Next.js构建时只会生成已知路径的页面,未知路径会在首次请求时动态生成。如果某个slug对应的Sanity文档不存在(比如已删除、未发布),client.fetch会返回undefined,组件直接解构post就会报错。
修复步骤
在getStaticProps中拦截不存在的post
在获取post后判断是否存在,若不存在则返回404:export async function getStaticProps(context) { const { slug = "" } = context.params; const post = await client.fetch(query, { slug }); if (!post) { return { notFound: true }; } return { props: { post } }; }组件内添加兜底判断
在组件开头先检查post是否存在,避免解构报错:export default function SinglePost({ post }) { if (!post) { return <div>文章不存在或加载中</div>; } const { title, imageUrl, publishedAt, description, topics, rescources, sourcecode, body = [], } = post; return( <div> <h1>{title}</h1> // 剩余代码... </div>) }确保paths与Sanity数据一致
可以在getStaticPaths中过滤掉未发布的文档,避免无效slug被生成:const paths = await client.fetch( `*[_type == "post" && defined(slug.current) && publishedAt < now()][].slug.current` );
内容的提问来源于stack exchange,提问作者Wanuja Ranasinghe
相关产品推荐
相关产品推荐

