如何在盖茨比中创建动态路线 [英] How to create dynamic route in gatsby

查看:82
本文介绍了如何在盖茨比中创建动态路线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用此 链接 设置了gatsby项目.它工作正常.

I have setup gatsby project using this link. It is working correctly.

现在,我知道如何通过在 pages 文件夹中定义组件来创建路由.但是现在我面临一个新的挑战,我需要创建一个动态路线,以便可以在其中传递我的 id (就像reactjs一样).

Now I know how to create route by defining the component inside the pages folder. But now I have a new challenge I need to create one dynamic route so that I can pass my id in it (Just like reactjs).

<Route path: "/path/:id"/>

我该如何在盖茨比做到这一点?

How do I do that in gatsby?

推荐答案

您必须明确告诉gatsby路径应该是动态的.从文档:

You have to explicitly tell gatsby that a path should be dynamic. From the docs:

// gatsby-node.js
// Implement the Gatsby API "onCreatePage". This is
// called after every page is created.
exports.onCreatePage = async ({ page, actions }) => {
  const { createPage } = actions

  // page.matchPath is a special key that's used for matching pages
  // only on the client.
  if (page.path.match(/^\/app/)) {
    page.matchPath = "/app/*"

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

,然后您可以在src/pages/app.js

import { Router } from "@reach/router"

const SomeSubPage = props => {
  return <div>Hi from SubPage with id: {props.id}</div>
}

const App = () => (
  <Layout>
    <Link to="/app/1">First item</Link>{" "}
    <Link to="/app/2">Second item</Link>{" "}

    <Router>
      // ...dynamic routes here
      <SomeSubPage path="/app/:id" />
    </Router>
  </Layout>
)

export default App

/app/*上的所有内容现在都将动态处理.您应该在道具中照常找到自己的ID.

Everything that goes to /app/* will be handled dynamically now. You should find your id as usual in the props.

看看他们的身份验证示例 https://github.com /gatsbyjs/gatsby/tree/master/examples/simple-auth

Have a look at their authentication example https://github.com/gatsbyjs/gatsby/tree/master/examples/simple-auth

这篇关于如何在盖茨比中创建动态路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆