React Router v6 嵌套路由无法生效

1,267 阅读1分钟

问题1 打开新路由404

解决方法:juejin.cn/post/707108…

devServer: {
  compress: true,
  port: 9000,
  hot: true,
  historyApiFallback: true, //当我们在子路由刷新的时候,会提示找不到界面。https://juejin.cn/post/7071086182116884487
}

问题2 React Router V6打不开嵌套路由

// react
import React from 'react';
import ReactDOM from "react-dom/client";
import {
    createBrowserRouter,
    RouterProvider,
    Route, Link, Router,
} from "react-router-dom";
// layout
import Layout from "@layout/index";
// pages
import About from "@pages/about";
import Main from "@pages/main";
​
const router = createBrowserRouter([
    {
        path: "/",
        element: <Layout />,
        children: [
            {
                path: "/",
                element: <Main />,
            },
            {
                path: "about",
                element: <About />,
            },
        ]
    },
]);
​
ReactDOM.createRoot(document.getElementById('root')).render(
    <React.StrictMode>
        <RouterProvider router={router} />
    </React.StrictMode>
)
​

这样的写法是没问题的,问题的根源在于Layout组件

// react
import React, {useEffect} from 'react';
// style
import styles from './index.module.scss'
// layout
import Footer from "@layout/footer";
import Header from "@layout/header";
import Sidebar from "@layout/sidebar";
​
​
type IProps = {
    children?: React.ReactNode
}
​
const Layout: React.FC<IProps> = ({ children }) => {
    return (
        <div className={styles.layout}>
            <Header />
            <div className={styles.content}>
                <Sidebar />
                {children}
            </div>
            <Footer />
        </div>
    )
};
​
export default Layout;

这么写让React Router无法识别嵌套元素,指定children是没有用的,正确的做法是使用Outlet组件

// react
import React, {useEffect} from 'react';
import {Outlet} from 'react-router-dom';
// style
import styles from './index.module.scss'
// layout
import Footer from "@layout/footer";
import Header from "@layout/header";
import Sidebar from "@layout/sidebar";
​
​
const Layout: React.FC = () => {
    return (
        <div className={styles.layout}>
            <Header />
            <div className={styles.content}>
                <Sidebar />
                <Outlet />
            </div>
            <Footer />
        </div>
    )
};
​
export default Layout;

Outlet组件是一个占位符,告诉 React Router 嵌套的内容应该放到哪里。