我认为您正在寻找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 会查看嵌套在 <Router /> 下的每个组件的 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 文件。如果您希望站点用户能够直接访问客户端路由,则需要设置您的服务器以适当地处理这些路由。