为了扩展@Minoru 提供的答案,Next 官方文档在example 中介绍了这种情况。
使用 getStaticPaths 和 getStaticProps 允许您在构建时创建动态页面,避免 404。
帖子动态页面的示例代码:
import { GetStaticPaths, GetStaticProps } from 'next';
const Post = ({ post }) => {
const { id, content } = post;
return (
<div>
<h1>Post {id}</h1>
<p>{content}</p>
</div>
);
};
export const getStaticPaths: GetStaticPaths = async () => {
// Get all posts via API, file, etc.
const posts = [{ id: '1' }, { id: '2' }, { id: '3' }, { id: '4' }, { id: '5' }]; // Example
const paths = posts.map(post => ({
params: { id: post.id },
}));
return { paths, fallback: false };
};
export const getStaticProps: GetStaticProps = async context => {
const postId = context.params?.id || '';
// Get post detail via API, file, etc.
const post = { id: postId, content: `I'm the post with id ${postId}!` }; // Example
return { props: { post } };
};
export default Post;
使用next build && next export 构建网站时,我们将在out 文件夹中看到 Next 创建了每个帖子页面
然后,当您导航到 /posts/3/ 时,您将看到 id 为 3 的帖子
作为参考,此docs 页面包含此案例和许多其他用例。