[英]Render Same Component With Multiple Paths React Router Dom
I was looking for the simplest way to render the same component but from different paths.我一直在寻找从不同路径渲染相同组件的最简单方法。
I have the following so that both "/"
and "/login"
render the Login component.我有以下内容,以便
"/"
和"/login"
呈现登录组件。
import React from "react";
import { Route, Switch, Redirect } from 'react-router-dom';
import './App.scss';
import Login from "../../login/Login";
const App = () => {
return (
<div className="App">
<div className="App-container">
<Switch>
<Route exact path={["/", "/login"]} component={() =>
<Login login={true} />}/>
<Redirect to="/" />
</Switch>
</div>
</div>
);
}
export default App;
This does appear to work, however, it returns an error in the console.这似乎确实有效,但是,它会在控制台中返回错误。
Warning: Failed prop type: Invalid prop 'path' of type 'array' supplied to 'Route', expected 'string'.
I'm trying to do this...我正在努力做到这一点...
<Route exact path={"/"} component={() => <Login login={true} />}/>
<Route exact path={"/login"} component={() => <Login login={true} />}/>
But with a shorter method, is this possible with react-router-dom
?但是使用更短的方法,这可能与
react-router-dom
吗? Any help would be greatly appreciated任何帮助将不胜感激
You could create an array that contains the paths /
and /login
and use map
on that array to render the same thing for both paths.您可以创建一个包含路径
/
和/login
的数组,并在该数组上使用map
为两个路径呈现相同的内容。
<Switch>
{["/", "/login"].map(path => (
<Route
key={path}
exact
path={path}
render={() => <Login login={true} />}
/>
))}
<Redirect to="/" />
</Switch>
If you wish to render the same component on the several routes, you can do this by specifying your path as a regular expression如果您希望在多个路由上呈现相同的组件,您可以通过将路径指定为正则表达式来实现
lets say you want to display 'Home' component for 'Home', 'User' and 'Contact' components then here is code.假设您想为“主页”、“用户”和“联系人”组件显示“主页”组件,那么这里是代码。
<Route path="/(home|users|contact)/" component={Home} />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.