有没有办法使用模板组件/页面使用 Gatsby 创建动态 slugs?

Mih*_*aru 4 slug reactjs strapi gatsby

我对 Gatsby 很陌生,我想知道是否可以创建自定义路由(slugs)作为模板。用例是:

  1. 访问/articles/name-of-the-article路线
  2. Article.js使用name-of-the-articleslug从 API(即 Strapi 无头 CMS)检索的信息填充的服务组件。

Mih*_*aru 6

经过一些调查,我发现使用gatsby-plugin-create-client-paths有一种更简单的方法。您需要做的就是使用yarn或安装它,npm然后在其中gatsby-config.js添加以下内容:

{
      resolve: `gatsby-plugin-create-client-paths`,
      options: { prefixes: [`/articles/*`] },
},
Run Code Online (Sandbox Code Playgroud)

这意味着每个请求 slug 像这样:/articles/the-slug将请求articles.js页面并使用LinkGatsby 提供的页面,您可以state像这样通过props传递 props :

<Link to="/articles/the-slug" state={{ slug: "the-slug", ...etc }}>Anchor Text</Link>

这样,src/pages/articles.js就成为了前缀为 slug 的模板页面/articles