Nested react-router Switch



尝试在我的dash组件中嵌套一个开关,如下所示。

App.js

import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import PrivateRoute from './PrivateRoute';
<Router>
<Switch>
<Route exact path='/login' component={Login} />
<PrivateRoute exact path='/dash' component={Dashboard} />
<Route component={NotFound} />
</Switch>
</Router>

Dashboard.js

import { Route, Switch, useRouteMatch } from 'react-router';
import Chats from '../chats/Chats';
import DashNav from './dash-nav/DashNav';
import Contacts from '../contacts/Contacts';
const Dashboard = () => {
let { path, url } = useRouteMatch();
return (
<div>
<DashNav url={url} />
<Switch>
<PrivateRoute path={path} component={Chats} />
<PrivateRoute path={`${path}/contacts`} component={Contacts} />
</Switch>
</div>
);
};

DashNav与url作为props传递。

<div>
<Link to={`${url}/contacts`}>Contacts</Link>
</div>

我想点击来自DashNav的链接并呈现{Contacts}而不是{Chats},但它导航到正确的url ('baseurl/dash/Contacts ')并呈现{NotFound}而没有{DashNav}。

有人知道为什么它不工作吗?

在父路由器(App.js)中:

<PrivateRoute> exact path='/dash' component={Dashboard} />

不应该有'exact'作为属性,而应该是:

<PrivateRoute> path='/dash' component={Dashboard} />

相关内容

  • 没有找到相关文章

最新更新