【问题标题】:Why does @reach/router route paths automatically to page directory name?为什么@reach/router 会自动将路径路由到页面目录名称?
【发布时间】:2020-04-26 03:02:12
【问题描述】:

我目前正在使用 Gatsby 和 @reach/router

我想将我的关于页面链接到“/profile”

我的路由器看起来像:

<Router>
  <Home path="/" />
  <About path="/profile" />
  <Blog path="/blog" />
  <Contact path="/contact" />
</Router>

为什么我的关于页面显示在“/about”而不是“/profile”上?

另外,你把你的路由器组件放在哪里?目前,上面的代码是我的 app.js 文件。这是最佳做法吗?

【问题讨论】:

  • 你试过了吗? reach.tech/router/example/basic 将“路径”更改为“到”。
  • Gatsby 使用您的主页名称进行路由。因此,如果您在 Page 文件夹中创建一个名为 about.js 的组件,则会为 /about 创建路由,该路由将为 about 页面提供服务

标签: javascript reactjs web gatsby reach-router


【解决方案1】:

我能够让@reach/router 与 Gatsby 一起工作的唯一方法是让我的所有路由都通过这样的高阶组件。我也将路由器嵌套在我的布局包装器中。 请记住,页面文件夹中的任何 js 都将自行提供(没有页脚/标题或任何东西都会保留),因此如果这是针对 SPA,您应该只在页面文件夹中拥有 index.js。 如果您需要更多结帐此 repo:https://github.com/foestauf/gatsby-starter-default-SPA 这不是我创建的,但我不记得在哪里找到它,这就是最终让 Gatsby SPA 为我点击的原因。

import { Router } from "@reach/router"

const LazyComponent = ({ Component, ...props }) => (
  <React.Suspense fallback={"<p>Loading...</p>"}>
    <Component {...props} />
  </React.Suspense>
)

const IndexPage = () => (
  <Layout>
    <h1>Hi people</h1>
    <Link to="/">Home</Link>
    <Link to="/contact/">Contact</Link>
     <Link to="/about-us/">About Us</Link>
    <Router>
      <Home path="/" />
      <LazyComponent Component={Contact} path="contact" />
      <LazyComponent Component={About} path="about-us" />
    </Router>
  </Layout>
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-17
    • 2020-07-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多