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

<Route path="/" element={<NewsSandBox />} />

NewsSandBox组件下的代码:

import React from "react";
import { HashRouter, Routes, Route } from "react-router-dom";
import SideMenu from "../../components/sandbox/SideMenu";
import TopHeader from "../../components/sandbox/TopHeader";
import Home from "../home/Home";

export default function NewsSandBox() {
  return (
    <div>
      <SideMenu></SideMenu>
      <TopHeader></TopHeader>
      <Routes>
        <Route path="/home" element={<Home />} />
      </Routes>
    </div>
  );
}

但是页面无法显示子路由的组件,没有匹配到"/home"路径:

You rendered descendant <Routes> (or called `useRoutes()`) at "/" (under <Route path="/">) but the parent route path has no trailing "*". This means if you navigate deeper, the parent won't match anymore and therefore the child routes will never render.

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

经查阅文档可知:
在 v6 中,所有路由路径始终是完全匹配,不再像 v4/5 中那样匹配路径前缀。父/根路径需要指定 * 通配符,以便它们现在可以进行"前缀"匹配,所以解决办法是加上通配符*

<Route path="/*" element={<NewsSandBox />} />

问题完美解决!

上一篇:使用git迁移git项目并保留提交记录


下一篇:数据库连接池libzdb的使用