如何在NextJS中通过getServerSideProps为每个文章条目生成单独页面
解决方案
场景1:保持服务端渲染(SSR,每次请求动态生成页面)
你现有代码的问题是没有从动态路由参数中获取当前访问的文章ID,也没有对返回的全量列表做过滤,修改如下:
function Article(props) { // 这里props.article就是当前ID对应的单篇文章数据 const { article } = props return <div> <h1>{article.title}</h1> {/* 其他文章内容渲染逻辑 */} </div> } export async function getServerSideProps(context) { // 1. 从动态路由参数中获取当前访问的文章id const { id } = context.params // 2. 拉取全量文章列表 const res = await fetch("https://.../articles"); const allArticles = await res.json() // 3. 过滤出当前ID对应的单篇文章 const currentArticle = allArticles.find(item => item.id === id) if (!currentArticle) { return { notFound: true, } } return { props: { article: currentArticle } } } export default Article
如果后端支持单篇文章查询接口,建议直接请求https://.../articles/${id},不需要拉全量列表过滤,性能更高。修改完成后访问/articles/1、/articles/2就会分别对应ID为1、2的独立文章页面。
场景2:静态生成所有文章页面(SSG,构建时生成,性能更优)
如果你的文章内容不会频繁变更,更推荐使用静态生成方案,需要配合getStaticPaths指定所有需要生成的文章ID:
function Article(props) { const { article } = props return <div> <h1>{article.title}</h1> {/* 其他文章内容渲染逻辑 */} </div> } // 构建时指定所有需要生成的文章路径 export async function getStaticPaths() { const res = await fetch("https://.../articles"); const allArticles = await res.json() // 生成所有文章对应的路径参数 const paths = allArticles.map(article => ({ params: { id: article.id } })) return { paths, // 设为false表示未在paths中指定的ID访问时直接返回404,设为true可支持增量静态生成 fallback: false } } // 针对每个路径获取对应文章数据 export async function getStaticProps(context) { const { id } = context.params const res = await fetch("https://.../articles"); const allArticles = await res.json() const currentArticle = allArticles.find(item => item.id === id) return { props: { article: currentArticle } } } export default Article
内容的提问来源于stack exchange,提问作者jonask
相关产品推荐
相关产品推荐

