react-router v6嵌套路由简单案例


react-router V6版本路由用法和V5用法差距较大,一个简单的使用案例

新版本组件也开始使用函数式组件+hooks

"react-router-dom": "^6.2.1",

1.入口main 

import "./App.css";
import { BrowserRouter, Route, Routes, Navigate } from "react-router-dom";
import Index from "./modules/index/Index";
import Error from "./modules/error/Index";
import Admin from "./modules/admin/Index";

const App = () => {
    return (
        
{/* HashRouter哈希路由 还是 Browser路由随需求选择 */} {/* 默认初始化入口/home*/} } /> {/* home模块路由 */} } /> {/* admin模块路由 */} } /> {/* 404页面 */} } />
); }; export default App;

2.子路由-Index模块(案例举例)

import { Route, Routes } from "react-router-dom";
import MainIndex from "./page/index/Index";
import Nav from "./page/nav/Nav";

import Error from "../error/Index";


const Index = () => {
    return (
        
{/* path="/"初始化默认 */} } /> } /> {/* 子路由的404页面 */} } />
); }; export default Index;

3.路由跳转方法2种 useNavigate, Link

import { useNavigate, Link } from "react-router-dom";

const Child = (props) => {
    const navigate = useNavigate();
    return (
        
{/* link跳转 */} 跳转路由
{ // 逻辑跳转 navigate("/admin/componentDelivery"); // replace 跳转 // navigate('/home', {replace: true}); // navigate("/"); // 回退步数 0刷新页面 // navigate(-1); }}>
); }; export default Child;

你可能感兴趣的:(react-router v6嵌套路由简单案例)