【发布时间】:2021-08-18 18:27:01
【问题描述】:
例如,我有一个动态路由/blog/[article-id]。
访问现有的博客文章/blog/id-that-exist 时,它按预期工作,现在我想妥善处理/blog/id-that-does-not-exist 的情况。
/blog/[id].jsx 中的代码类似于:
export const getStaticPaths async () => {
return {
fallback: true,
paths: (await sequelize.models.Article.findAll()).map(
article => {
return {
params: {
pid: article.slug,
}
}
}
),
}
}
export const getStaticProps async () => {
// Try to get it from the database. Returns none if does not exist.
const article = await sequelize.models.Article.findOne({
where: { slug: pid },
});
return { props: { article: article } };
}
const ArticlePage = (props) => {
// This can happen due to fallback: true while waiting for
// a page that was not rendered at build time to build.
const router = useRouter()
if (router.isFallback) {
return <div>loading</div>;
}
return (
<div>{props.article.body}</div>
);
};
export const getStaticPaths = getStaticPathsArticle;
export const getStaticProps = getStaticPropsArticle;
export default ArticlePage;
我看到了这个相关的问题:How to handle not found 404 for dynamic routes in Next.js which is calling API?,但我不确定它是否和我在这里问的一样,因为这不依赖于正在使用的任何外部 API。
【问题讨论】:
标签: next.js