问题1 打开新路由404
解决方法:https://juejin.cn/post/7071086182116884487
1 2 3 4 5 6
| devServer: { compress: true, port: 9000, hot: true, historyApiFallback: true, }
|
问题2 React Router V6打不开嵌套路由
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| import React from 'react'; import ReactDOM from "react-dom/client"; import { createBrowserRouter, RouterProvider, Route, Link, Router, } from "react-router-dom";
import Layout from "@layout/index";
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组件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| import React, {useEffect} from 'react';
import styles from './index.module.scss'
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组件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| import React, {useEffect} from 'react'; import {Outlet} from 'react-router-dom';
import styles from './index.module.scss'
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 嵌套的内容应该放到哪里。