【问题标题】:Multiple path names for a same component in Reach Router到达路由器中同一组件的多个路径名
【发布时间】:2020-02-03 12:37:46
【问题描述】:

我在三个不同的路线上使用相同的组件:

<Router>
    <Home path="/" />
    <Home path="/home" />
</Router>

有没有办法把它结合起来,就像:

<Router>
    <Home path=["/home", "/"] />
</Router>

【问题讨论】:

标签: javascript reactjs url-routing reach-router


【解决方案1】:

对于到达路由器:(https://reach.tech/router/example/)

使用显示的确切示例,我可以看到如何执行此操作(在单行上)的唯一方法是使用通配符。

要找到一种在没有副作用的情况下重现此内容的方法,我们需要查看整个导航菜单。

  <Router>
    <Home path="/*" />
    <Chicken path="chicken">
  </Router>

...

const Home = props => {
  let urlPath = props["*"]
  // URL: "/home"
  // urlPath === "home"
  // URL/: "/"
  // urlPath ===""
}

您可以继续使用 Home 下面的其他路径,路由器将允许它们处理。

查看the example using a wildcard and reach router on codesandbox, I wrote!

注意:这是一个包罗万象的方法,但不解析参数是我看到的唯一单行解决方案。

一些缺点包括 Home 渲染而不是“404”等。

//这可以通过渲染中的 if 语句来解决

//它也不会为 /home 生成预期的 URL,我没有调查过,因为它不是问题的一部分。但如果它匹配 props[*],我相信你可以重定向或东西。

您可以阅读有关 Reach Router 的 Route 组件的更多信息。 https://reach.tech/router/api/RouteComponent

【讨论】:

  • 第一个链接坏了。
【解决方案2】:

我对文档和@cullen-bond 中的通配符解决方案不满意,因为我必须映射许多其他路径并想出了这个解决方案:

<Router>
  {["/home", "/", "/other", "/a-lot-more"].map(page => <Home path={page} />)}
</Router>

示例:https://codesandbox.io/s/reach-router-starter-v1-forked-6f44c?file=/src/index.js

【讨论】:

    【解决方案3】:

    我认为你可以随心所欲。看看这个:https://reacttraining.com/react-router/core/api/Route/path-string-string

    【讨论】:

    • 我使用 Reach Router 而不是 React Router,更多 => reach.tech/router
    • 啊,对不起,我以为是错字:)
    【解决方案4】:

    您可以通过使用路由数组将单个组件用于多个路径。

    代码示例:

    从'./sampleComponent'导入sampleComponent; // 多个路由的单个组件

     <Router>
      <Switch>
       {["/pathname_1", "/pathname_2", "/pathname_3", "/pathname_4", "/pathname_5", "/pathname_6"].map(pathname =>  (<Route exact path={pathname} component={sampleComponent} />) )}
       <Switch>
    <Router>
    

    【讨论】:

    • 那是 React Router 的,我正在寻找 Reach Router 的解决方案
    猜你喜欢
    • 2019-10-14
    • 1970-01-01
    • 2018-07-11
    • 2019-12-10
    • 1970-01-01
    • 2017-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多