【问题标题】:Nested react-router Switch嵌套反应路由器开关
【发布时间】:2021-09-10 15:30:32
【问题描述】:

尝试在我的仪表板组件中嵌套一个开关,如 here 所述。

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>

仪表板.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>
    );
};

将 url 作为 props 传递的 DashNav。

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

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

谁能看出它为什么不起作用?

【问题讨论】:

  • DashNav 中定义的 url 是什么?
  • 控制台日志'/dash'

标签: reactjs react-router react-router-dom


【解决方案1】:

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

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

不应将“精确”作为属性,而应为:

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

【讨论】:

    猜你喜欢
    • 2019-02-18
    • 1970-01-01
    • 1970-01-01
    • 2016-08-18
    • 1970-01-01
    • 2017-07-23
    • 2017-08-06
    • 1970-01-01
    • 2020-11-19
    相关资源
    最近更新 更多