解决react-router-dom V6路由嵌套时子路由无法显示的问题

父组件

class App extends Component {
  render() {
    return (
      <Router>
        <Routes>
          <Route path="/app" element={<ThisLayout />} />
        </Routes>
      </Router>
    );
  }
}

子组件ThisLayout下的代码

class ThisLayout extends Component {
  render() {
    return (
      <div className="App">
        <Layout>
        	<HeaderPage />
            <Routes>
                <Route path="/app/index" element={<ContentPage />} />
            </Routes>
        </Layout>
      </div>
    )
  }
};

http://localhost:3000/app会显示HeaderPage组件的内容
http://localhost:3000/app/index却没有显示ContentPage组件的内容。
经查验得知,在 v6 中,所有路由路径始终是完全匹配,不再像 v4/5 中那样匹配路径前缀。父/根路径需要指定 * 通配符,以便它们现在可以进行"前缀"匹配,所以解决办法是加上通配符*

父组件增加一行<Route path="/*" element={<ThisLayout />} />即可,修改如下

class App extends Component {
  render() {
    return (
      <Router>
        <Routes>
          <Route path="/*" element={<ThisLayout />} />
          <Route path="/app" element={<ThisLayout />} />
        </Routes>
      </Router>
    );
  }
}

猜你喜欢

转载自blog.csdn.net/frank7023/article/details/128913988