[英]having multiple paths to the same component in react-router-dom v6
i'm trying to have multiple paths/routes in react router v6 to render the same component我正在尝试在 react router v6 中使用多个路径/路由来呈现相同的组件
using previous versions of react router dom i could just do this and it would work:使用以前版本的 react router dom 我可以这样做并且它会起作用:
<Route exact path={["/", "/home"]}>
<Home />
</Route>
<Route exact path={"/" | "/home"}>
<Home />
</Route>
now using v6 i'm trying the same thing but it doesn't work现在使用 v6 我正在尝试同样的事情,但它不起作用
<Route exact path={["/","/home"]} element={<Homepage />} />
how should i go about this?我应该如何解决这个问题 go? what changed exactly for it not to work?到底是什么改变了它不起作用?
full code of App.js where i do the routing我进行路由的 App.js 的完整代码
import React from 'react';
import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom'
import Navbar from './components/Navbar';
import Footer from './components/Footer';
import Contact from './components/Contact';
import Homepage from './components/Homepage';
import Projects from './components/Projects'
function App() {
return (<Router>
<Navbar />
<Routes>
<Route exact path={["/","/home"]} element={<Homepage />} />
<Route exact path="/contact" element={<Contact/>} />
<Route exact path="/projects" element={<Projects />} />
</Routes>
<Footer />
</Router>);
}
export default App;
It's component
not element
它是component
而不是element
Try this:尝试这个:
<Route exact path={["/","/home"]} component={<Homepage />} />
Probably not a good idea to be repeating the code as the accepted answer suggests, easy to break when the call to the components to load changes.正如公认的答案所暗示的那样重复代码可能不是一个好主意,当对组件的调用发生变化时很容易中断。
Just map over the array to create the routes:只需 map 在阵列上创建路由:
{["/", "/home"].map((path, index) => {
return (
<Route path={path} element={
<PageWrapper>
<Home />
</PageWrapper>
}
key={index}
/>
);
})}
Another option is to useRoutes just the nav and put them as sibling to some of the <Routes />
另一种选择是仅使用导航并将它们作为某些<Routes />
的同级
Gist from how I'm using it:我如何使用它的要点:
import React from 'react';
import { Route, Routes, useRoutes } from 'react-router-dom';
import Nav from './components/common/nav';
export const App: React.FC = () => {
const element = useRoutes([
{ path: '/', element: <Nav /> },
{ path: '/equipment', element: <Nav /> },
{ path: '/client-area/*', element: <Nav /> },
]);
return (
<main>
{element}
<Routes>
<Route />
<Route />
<Route />
{/* Your routes here */}
</Routes>
</main>
);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.