【问题标题】:Nested routes with react-router v5 doesn't update layoutreact-router v5 的嵌套路由不会更新布局
【发布时间】:2021-04-23 11:02:27
【问题描述】:

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

考试列表应链接到学生列表。

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

/ 点击链接 [to Students] 不会呈现学生组件,但如果我刷新浏览器,学生组件将正确呈现。

/students 点击链接 [to Exams] 效果很好。

【问题讨论】:

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


    【解决方案1】:

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

    所以从这里更改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,了解从这里去哪里/如何处理一般的嵌套路线。

    【讨论】:

      猜你喜欢
      • 2021-03-22
      • 2020-10-10
      • 2018-01-11
      • 2020-06-05
      • 2016-11-12
      • 2021-03-02
      • 1970-01-01
      • 2020-07-21
      • 1970-01-01
      相关资源
      最近更新 更多