在Next.js的getStaticProps中数据无效时如何重定向到404页面?
解决方法
Next.js的getStaticProps方法原生支持返回notFound: true配置,当检测到请求的作者ID不存在时返回该配置,框架会自动跳转到404页面。你出现报错的原因是无效ID请求接口时,返回的作者数据为空,前端直接读取嵌套属性触发了类型错误。
1. 修改getStaticProps逻辑
需要先捕获接口请求的异常,同时校验返回的作者数据是否有效,无效时直接返回404:
export async function getStaticProps(context) { const { params: { authorId }, } = context; try { const fetchArticles = await axios.get( `http://localhost:3000/api/articles/${authorId}/1` ); const fetchAuthor = await axios.get( `http://localhost:3000/api/articles/authors/${authorId}` ); // 校验作者数据是否存在 if (!fetchAuthor.data?.author) { return { notFound: true, } } return { props: { Articles: fetchArticles.data, Author: fetchAuthor.data, }, revalidate: 60, }; } catch (err) { // 接口请求出错(比如无效ID返回404、参数非法)时返回404 return { notFound: true, } } }
2. 可选:组件层加兜底兼容
由于你设置了fallback: true,用户首次访问未预生成的作者页面时,Next.js会先返回 fallback 状态,此时页面props还未加载完成,建议在组件中加双重校验避免偶发报错:
import { useRouter } from 'next/router' const AuthorProfilePage = ({ Articles, Author }) => { const router = useRouter() // fallback状态下展示加载提示 if (router.isFallback) { return <div>页面加载中...</div> } return <> <div className={styles.authorImgContainerBig}> <Image // 用可选链兜底,避免属性读取报错 src={Author?.author?.photo?.url || "https://res.cloudinary.com/bizimsehir-gazetesi/image/upload/v1624802793/blank-profile-picture-973460_1280_duksmn.png"} className={styles.authorImgBig} layout="fill" objectFit="cover" quality={100} alt="" /> </div> </> }
如果需要自定义404页面的样式,只需要在项目pages目录下新建404.js文件编写对应的页面代码即可,返回notFound: true时会自动渲染该自定义页面。
内容的提问来源于stack exchange,提问作者Bob Stone
相关产品推荐
相关产品推荐

