带有 react-router v5 的嵌套路由不会更新布局

Nested routes with react-router v5 doesn't update layout

我想将我的应用分成两个不同的部分。

考试列表应该 link 到学生列表。

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter, Link, Route, Switch, useRouteMatch } from 'react-router-dom';

// doesn't work
const ExamList = () => {
    return (
        <p>
            current: ExamList ,<Link to='/students'>to Students</Link>
        </p>
    );
};

// nested router
const Exams = () => {
    let { path, url } = useRouteMatch();
    return (
        <BrowserRouter>
            <Switch>
                <Route exact path={path}>
                    <ExamList />
                </Route>
            </Switch>
        </BrowserRouter>
    );
};

// worked 
const Students = () => {
    return (
        <p>
            current: Students ,<Link to='/'>to Exams</Link>
        </p>
    );
};

ReactDOM.render(
    <BrowserRouter>
        <Switch>
            <Route exact path='/'>
                <Exams />
            </Route>
            <Route path='/students'>
                <Students />
            </Route>
        </Switch>
    </BrowserRouter>,
    document.getElementById('root')
);

/ 点击 link [to Students] 不渲染 Students 组件,但如果我刷新浏览器,Students 组件将被渲染。

/students 点击 link [to Exams] 工作正常。

问题在于您不仅在嵌套路由,还在嵌套路由器。

所以将 Exams 改成:

const Exams = () => {
  let { path, url } = useRouteMatch();
  return (
    <BrowserRouter>
      <Switch>
        <Route exact path={path}>
          <ExamList />
        </Route>
      </Switch>
    </BrowserRouter>
  );
};

对此:

const Exams = () => {
  let { path, url } = useRouteMatch();
  return (
    <Switch>
      <Route exact path={path}>
        <ExamList />
      </Route>
    </Switch>
  );
};

我建议您看一下这个 example 以了解从这里去哪里/一般如何处理嵌套路由。