我对三个不同的路线使用相同的组件:
<Router>
<Home path="/" />
<Home path="/home" />
</Router>
反正有没有把它结合起来,就像:
<Router>
<Home path=["/home", "/"] />
</Router>
我对三个不同的路线使用相同的组件:
<Router>
<Home path="/" />
<Home path="/home" />
</Router>
反正有没有把它结合起来,就像:
<Router>
<Home path=["/home", "/"] />
</Router>
对于到达路由器:(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 下面的其他路径,路由器将允许它们处理。
注意:这是一个包罗万象的方法,但不解析参数是我看到的唯一单行解决方案。
一些缺点包括 Home 渲染而不是“404”等。
//这可以通过渲染中的 if 语句来解决
//它不会为/home生成预期的URL,我没有调查过,因为它不是问题的一部分。但如果它匹配props [*],我相信你可以重定向或其他东西。
您可以阅读有关 Reach Router 的 Route 组件的更多信息。 https://reach.tech/router/api/RouteComponent
我对文档和@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
根据您正在处理的情况,<Redirect />
也可以完成工作。
<Router>
<Redirect from="/" path="/home" noThrow />
<Home path="/home" />
</Router>
我认为您可以按照自己的意愿进行操作。看看这个:https ://reacttraining.com/react-router/core/api/Route/path-string-string
通过使用路由数组,您可以将单个组件用于多个路径。
代码示例:
从'./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>