【问题标题】:How to create custom routes on top of programmatically created pages in gatsby如何在 gatsby 中以编程方式创建的页面之上创建自定义路由
【发布时间】:2020-03-05 23:34:01
【问题描述】:

我正在尝试以编程方式创建具有动态路由的页面,但遇到了无法创建动态路由的问题。

在我的 gatsby-node.js 中有

exports.createPages = async ({ graphql, actions }) => {
  const { createPage } = actions

  {...graphql query}

  locations.forEach(edge => {
    createPage({
      path: `/${edge.node.path}/details`,
      component: path.resolve(`./src/templates/detailsTemplate.js`),
      context: { name: edge.node.name }
    })
  })
}

exports.onCreatePage = async ({ page, actions }) => {
  const { createPage } = actions

  if (page.path.match(/^(.*?)\/details/)) {
    page.matchPath = "/details/*"

    // Update the page.
    createPage(page)
  }
}

我的 gatsby-config.js 是:

    {
      resolve: `gatsby-plugin-create-client-paths`,
      options: { prefixes: [`/details/*`] },
    },

然后我使用到达路由器创建路由: :位置/详细信息/常见问题解答 :位置/详细信息/联系方式 等等……

但是它没有正确匹配路由。

【问题讨论】:

    标签: gatsby


    【解决方案1】:

    将变量(您的动态路由)传递到生成的页面的唯一方法是通过context

    您需要在exports.onCreatePage = ({ page, actions }) => {...} 中的gatsby-node.js 中设置您的路线:

    exports.onCreatePage = ({ page, actions }) => {
      const { createPage } = actions
      createPage({
        path: node.fields.slug,
        component: path.resolve(`./src/templates/yourTemplate.js`),
    
        // ## PASS YOUR ROUTES HERE ##
    
        context: {
          faq: `faq/route`,
          contact: `contact/route`,
          etc: `etc/route`,
        },
      })
    }
    

    然后在yourTemplate.js中设置你的路线:

    const Article = ({ pageContext }) => {
    
      // Your routes are inside the pageContext prop
      console.log(pageContext.faq)
      // ...
    }
    

    article 讨论了一个与您类似的用例和问题。

    【讨论】:

    • 谢谢,我确实把事情复杂化了
    猜你喜欢
    • 1970-01-01
    • 2019-09-03
    • 2019-12-16
    • 1970-01-01
    • 1970-01-01
    • 2018-06-23
    • 2020-04-29
    • 2021-06-09
    • 1970-01-01
    相关资源
    最近更新 更多