如何在盖茨比中创建动态路线

时间:2019-04-19 05:25:01

标签: reactjs react-router gatsby

我使用此link设置了gatsby项目。它工作正常。

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

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

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

3 个答案:

答案 0 :(得分:2)

您必须明确告诉gatsby路径应该是动态的。来自http://10.XXX.15.XX/ClientExt/NewAPI/api.asmx

// 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

中使用动态路由
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。

看看他们的身份验证示例docs

答案 1 :(得分:1)

您可以在文件路径中使用方括号 ([ ]) 来标记 URL 的任何动态段。例如,为了编辑用户,您可能需要像 /user/:id 这样的路由来获取传递到 URL 中的任何 id 的数据。

src/pages/users/[id].js 将生成类似 /users/:id 的路线 src/pages/users/[id]/group/[groupId].js 将生成类似于 /users/:id/group/:groupId

的路线

参考:https://www.gatsbyjs.com/docs/reference/routing/file-system-route-api#creating-client-only-routes

答案 2 :(得分:0)

您可以使用gatsby-plugin-create-client-paths。它使用matchPath。有关更多信息,请检查

  1. https://www.gatsbyjs.org/docs/gatsby-internals-terminology/#matchpath
  2. https://www.gatsbyjs.org/packages/gatsby-plugin-create-client-paths/
相关问题