【问题标题】:Gatsby wildcard route盖茨比通配符路线
【发布时间】:2021-09-27 19:32:03
【问题描述】:

不能用通配符路径路由到同一个组件吗? 如果在 React 我有类似的东西:

<Router>
   <Switch>
      <Route path="/path/:id" children={<Component />} />
   </Switch>
</Router>

所有请求:

/path/123
/path/123/p
/path/123/p/1

将路由到相同的/path/123

我怎样才能告诉盖茨比也这样做?

createPage({
  path: `/path/123/*`,
  component,
  context
})

或者这个问题的解决方案是什么,某种重定向引擎?

【问题讨论】:

    标签: reactjs redirect routes gatsby


    【解决方案1】:

    我认为您正在寻找client-only routes。给定一个页面(或模板,如果它是从 gatsby-node.js 创建的),您可以:

    import React from "react"
    import { Router } from "@reach/router"
    import Layout from "../components/Layout"
    import SomeComponent from "../components/SomeComponent"
    
    const App = () => {
      return (
        <Layout>
          <Router basepath="/app">
            <SomeComponent path="/path" />
          </Router>
        </Layout>
      )
    }
    
    export default App
    

    注意:假设一个 src/pages/app/[...].js 页面 (File System Route API structure)。

    当页面加载时,Reach Router 会查看嵌套在 &lt;Router /&gt; 下的每个组件的 path 属性,并选择一个与 window.location 最匹配的组件进行渲染(您可以从 @reach/router 文档中了解有关路由工作原理的更多信息)。

    或者,您可以通过以下方式使用自动化方法(插件:gatsby-plugin-create-client-paths):

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

    这将验证/path 下的所有路由。

    或者对于更可定制的方法,在您的gatsby-node.js

    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(/^\/path/)) {
        page.matchPath = "/path/*"
    
        // Update the page.
        createPage(page)
      }
    }
    

    免责声明:这些路由仅存在于客户端上,不会对应于应用程序构建资产中的index.html 文件。如果您希望站点用户能够直接访问客户端路由,则需要设置您的服务器以适当地处理这些路由。

    【讨论】:

      猜你喜欢
      • 2020-07-02
      • 1970-01-01
      • 2020-10-16
      • 2019-08-07
      • 1970-01-01
      • 2021-12-14
      • 2022-08-19
      • 2021-07-30
      • 1970-01-01
      相关资源
      最近更新 更多