如何在不运行npm run build命令的情况下在nextjs中添加新的博客文章时呈现动态路由 &



我在nextjs中开发了一个博客应用程序,在数据库中添加新博客时,它不会用新路由渲染页面,而是我必须手动执行npm run build来预渲染新博客。在此之前,它一直显示未找到错误。

export async function getStaticPaths() {
const posts = await service.getAllPosts();
const paths = posts.map((post) => ({
params: { slug: post.slug },
}));
return { paths, fallback: 'blocking' };
}
export async function getStaticProps({
params,
}: GetStaticPropsContext<{ slug: string }>) {
const slug = params?.slug as string;
try {
const { post } =
await service.getPost(slug);
return {
props: { post },
revalidate: 10,
};
} catch (error) {
return { props: { post: {}, error: error.message} };
}
}
const Blog = ({ post }: Props) => {
return <div>
<p>{post.title}
</div>

}

我不知道我哪里做错了。

当我添加一个新的博客文章,我不渲染在客户端当我访问:https://example.com/blog/new-slug

这是因为你正在使用getStaticProps,它只在网站构建时被调用。这对于不经常更改的页面很有用。

如果你想让网站随时更新你发布的东西,你应该使用getServerSideProps,每次你访问页面时调用。

或者你也可以做客户端抓取,如果你不介意SEO。

如果您想保持静态页面的性能,另一种方法是使用getStaticProps中的revalidate选项。它告诉页面在一段时间间隔后重新构建。

最新更新