如何将所有路线重定向到盖茨比索引

问题描述

我正在尝试创建一个只有一页来处理所有路线的Gatsby项目。我有这样的索引页面

const App = () => {
  return <Router>
    <Home path="/"/>
    <Login path="/login" />
    <Content path="/content" />
  </Router>
}

src/pages文件夹中,我只有index.js

如何使此页面处理所有路线?

检查盖茨比文档(https://www.gatsbyjs.com/docs/client-only-routes-and-user-authentication/)我知道我可以像这样使用插件gatsby-plugin-create-client-paths

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

如果我使用React路由器制作一个名为app.js页面,这将很好地工作。因此,所有路线/app/*都转到此页面

但是如何在根URL /上进行这种重定向。我想使任何路由/*都进入索引页:index.js

有关如何执行此操作的任何建议? :)

解决方法

像这样设置index.js

const IndexPage = () => {
  return (
    <Router>
      <Home path="/"/>
      <Login path="/login" />
      <Content path="/content" />
    </Router>
  )
}

export default IndexPage

gatsby-node.js中的

exports.onCreatePage = ({ page,actions }) => {
  const { createPage } = actions
  if (page.path === `/`) {
    page.matchPath = `/*`
    createPage(page)
  }
}

重新启动gatsby develop,索引页面将处理您设置的路由。