盖茨比:生成嵌套动态路由

时间:2019-12-11 19:14:07

标签: gatsby

我正在尝试生成一些仅用于客户端的路由。

我需要匹配的网址如下

/ products / anything / this-page

有些gatsby生成的网址看起来像/ products / anything /

我尝试过:

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

    if (page.path.match(/^\/product/)) {
        // eslint-disable-next-line no-param-reassign
        page.matchPath = `/product/*`
        createPage(page)
    }
}

无济于事...

还有一个更复杂的正则表达式

   if (page.path.match(/^product\/.*\/.*/)) {
        // eslint-disable-next-line no-param-reassign
        page.matchPath = /^product\/.*\/.*/
        createPage(page)
    }

2 个答案:

答案 0 :(得分:0)

在onCreatePage函数中,您可以动态创建页面的网址:

// The all allWcProduct is a custom node I've added, but could be replaced with 
another node you have on your site instead.
const path = require("path")
const pageQuery = `
    {
      allWcProduct{
        edges{
          node{
            slug
            name
          }
        }
      }
    }
    `

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

  return new Promise((resolve, reject) => {
    graphql(pageQuery).then(results => {

      if (results.errors) {
        console.log(results.errors)
        reject(results.errors)
      }
      results.data.allWcProduct.edges.forEach(({ node }) => {
        createPage({
          path: `/products/${node.slug}`,
          component: path.resolve(`./src/components/products/productDetailPage.tsx`),
          context: {
            slug: node.slug // send this to the component itself as a prop
          }
        })
      })
    })
    resolve()
  })

}

如上所述,您也可以将插件用于更基本的用途。

答案 1 :(得分:0)

我找到了一种在动态 slug 之后创建嵌套路由的解决方案。在您的 gatsby-node.js 文件中:

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

  const { data } = await graphql(`
    query {
      //your query here
    }
  `)

  data.allProducts.edges.forEach(edge => {
    const slug = edge.node.productId
     
    //create your dynamic page

    createPage({
      path: `/products/${slug}/`,
      component: require.resolve(
        "./src/components/products/templates/product-template/ProductTemplate.tsx"
      ),
      context: { productData: edge.node },
    })

    //create nested route in it

    createPage({
      path: `/products/${slug}/something/`,
      component: require.resolve(
        "./src/components/trainings/templates/something/something.tsx"
      ),
      context: { productData: edge.node },
    })
  })
}
相关问题