Next.js 9.3+ 和包罗万象的路线

Bry*_*ray 1 javascript blogs next.js getstaticprops getstaticpaths

Next.js 初学者,希望获得有关使用getStaticPathsgetStaticProps包罗万象的路线的指导。大多数 Next.js 9.3+ 博客入门者似乎仅基于一个级别的博客文章(例如,/posts/post-1.md/posts/post-2.md等),但我徒劳地尝试找到的是入门者 \xe2\x80\x94 或只是一个一组指令 \xe2\x80\x94 ,用于解决处理问题,例如/posts/yyyy/mm/postname.md通过/pages/posts/[...post].js.

\n

当然,我确实阅读了有关这些项目的 Next.js 文档,但我发现它们至少在这种特殊情况下缺乏帮助。我确实意识到它们是为更有经验的 Next.js 开发人员编写的。这一项来自https://nextjs.org/docs/routing/dynamic-routes,让我尽可能接近目前的情况,但还不够远:

\n
\n

如果页面名称使用 catch-all 路由,例如pages/[...slug]params则应包含slugwhich 是一个数组。例如,如果该数组为[\'foo\', \'bar\'],则 Next.js 将静态生成位于 的页面/foo/bar

\n
\n

我尝试使用fs-readdir-recursive读取/posts/目录的各个级别并且可以工作,但是它给我的并没有产生getStaticPaths想要的数组。我确定我只需要调整结果,但找不到任何示例来帮助我弄清楚。(大多数比一级场景更进一步的例子似乎都是处理从数据库中获取数据,也许是因为我试图找到的场景被认为太简单了。对于非初学者来说,可能是这样,但是......)

\n

Ber*_*ron 6

如果您的帖子都遵循相同的 URL 模式,我宁愿使用以下结构:

\n
pages/\n\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 posts/\n    \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 [year]/\n        \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 [month]/\n            \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 [slug].js\n
Run Code Online (Sandbox Code Playgroud)\n

根据您\xe2\x80\x99存储帖子的方式,您getStaticPaths只需列出帖子并公开每个帖子的year,month和。slug

\n
export async function getStaticPaths() {\n  const posts = await getAllPosts()\n\n  return {\n    fallback: false,\n    paths: posts.map(post => ({\n      params: {\n        year: post.year,\n        month: post.month,\n        slug: post.slug\n      }\n    })\n  }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

然后你\xe2\x80\x99就year可以访问.monthsluggetStaticProps

\n
export async function getStaticProps({params}) {\n  // Retrieve blog post from year, month and slug\n  const post = await getBlogPost({\n    year: params.year,\n    month: params.month,\n    slug: params.slug\n  })\n\n  return {\n    props: {\n      post\n    }\n  }\n}\n
Run Code Online (Sandbox Code Playgroud)\n