简体   繁体   English

react-router v5 的嵌套路线不会更新布局

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

I want to split my app in 2 different parts.我想将我的应用分成 2 个不同的部分。

An exam list should link to a student list.考试列表应链接到学生列表。

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')
);

/ click the link [to Students] doesn't render Students component, but if I refresh the browser, the Students component will be rendered currectly. /单击链接 [to Students] 不会呈现学生组件,但如果我刷新浏览器,学生组件将正确呈现。

/students click the link [to Exams] worked fine. /students点击链接 [to Exams] 工作正常。

The problem is that you're not just nesting routes, but you're also nesting routers.问题是您不仅在嵌套路由,而且还在嵌套路由器。

So change Exams from this:所以从这里改变Exams

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

to this:对此:

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

I recommend you take a look at this example for a good idea of where to go from here / how to approach nested routes in general.我建议你看一下这个例子,了解从这里到 go 的位置/如何处理一般的嵌套路由。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM