Skip to content
On this page

router V6 的基础运用

bash
 yarn add react-router-dom
1

https://reactrouter.com/en/main

基础应用

App.jsx

jsx
import React from "react";
import { HashRouter, Routes, Route, Navigate } from 'react-router-dom';
import HomeHead from './components/HomeHead';

/* 导入需要的组件 */
import A from './views/A';
import B from './views/B';
import C from './views/C';
import A1 from './views/a/A1.jsx';
import A2 from './views/a/A2.jsx';
import A3 from './views/a/A3.jsx';

const App = function App() {
    return <HashRouter>
        <HomeHead />
        <div className="content">
            <Routes>
                {/* 一级路由 「特殊属性 index」*/}
                <Route path="/" element={<Navigate to="/a" />} />
                <Route path="/a" element={<A />} >
                    {/* 二级路由 */}
                    <Route path="/a" element={<Navigate to="/a/a1" />} />
                    <Route path="/a/a1" element={<A1 />} />
                    <Route path="/a/a2" element={<A2 />} />
                    <Route path="/a/a3" element={<A3 />} />
                </Route>
                <Route path="/b" element={<B />} />
                <Route path="/c" element={<C />} />
                <Route path="*" element={<Navigate to="/a" />} />
            </Routes>
        </div>
    </HashRouter>;
};
export default App;
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

跳转及传参

jsx
// C组件的路由地址
<Route path="/c/:id?/:name?" element={<C />} />

/* 跳转及传参 */
import { useNavigate } from 'react-router-dom';
const B = function B() {
    const navigate = useNavigate();
    return <div className="box">
        B组件的内容
        <button onClick={() => {
            navigate('/c');
            navigate('/c', { replace: true });
            navigate(-1);
            navigate({
                pathname: '/c/100/zxt',
                search: 'id=10&name=zhufeng'
            });
            navigate('/c', { state: { x: 10, y: 20 } });
        }}>按钮</button>
    </div>;
};
export default B;

/* 接收信息 */
import { useParams, useSearchParams, useLocation, useMatch } from 'react-router-dom';
const C = function C() {
    //获取路径参数信息
    let params = useParams();
    console.log('useParams:', params);

    //获取问号传参信息
    let [search] = useSearchParams();
    search = search.toString();
    console.log('useSearchParams:', search);

    //获取location信息「pathname/serach/state...」
    let location = useLocation();
    console.log('useLocation:', location);

    //获取match信息
    console.log('useMatch:', useMatch(location.pathname));

    return <div className="box">
        C组件的内容
    </div>;
};
export default C;
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
38
39
40
41
42
43
44
45
46
47

路由表及懒加载

router/index.js

JavaScript
import React, { Suspense } from "react";
import { Route, Routes, useNavigate, useParams, useSearchParams, useLocation, useMatch } from 'react-router-dom';
import routes from "./routes";

// 渲染内容的特殊处理
const Element = function Element(props) {
    let { component: Component, path } = props,
        options = {
            navigate: useNavigate(),
            params: useParams(),
            query: useSearchParams()[0],
            location: useLocation(),
            match: useMatch(path)
        };
    return <Component {...options} />;
};

// 递归创建路由规则
const createRoute = function createRoute(routes) {
    return <>
        {routes.map((item, index) => {
            return <Route key={index} path={item.path} element={<Element {...item} />}>
                {item.children ? createRoute(item.children) : null}
            </Route>;
        })}
    </>;
};

// 路由表管控
const RouterView = function RouterView() {
    return <Suspense fallback={<>正在加载中...</>}>
        <Routes>
            {createRoute(routes)}
        </Routes>
    </Suspense>;
};
export default RouterView;
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

router/routes.js

JavaScript
import { lazy } from 'react';
import { Navigate } from 'react-router-dom';
import A from '../views/A';
import aRoutes from './aRoutes';

const routes = [{
    path: '/',
    component: () => <Navigate to="/a" />
}, {
    path: '/a',
    name: 'a',
    component: A,
    meta: {},
    children: aRoutes
}, {
    path: '/b',
    name: 'b',
    component: lazy(() => import('../views/B')),
    meta: {}
}, {
    path: '/c',
    name: 'c',
    component: lazy(() => import('../views/C')),
    meta: {}
}, {
    path: '*',
    component: () => <Navigate to="/a" />
}];
export default routes;
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

router/aRoutes.js

JavaScript
import { lazy } from 'react';
import { Navigate } from 'react-router-dom';
const aRoutes = [{
    path: '/a',
    component: () => <Navigate to="/a/a1" />
}, {
    path: '/a/a1',
    name: 'a-a1',
    component: lazy(() => import('../views/a/A1')),
    meta: {}
}, {
    path: '/a/a2',
    name: 'a-a2',
    component: lazy(() => import('../views/a/A2')),
    meta: {}
}, {
    path: '/a/a3',
    name: 'a-a3',
    component: lazy(() => import('../views/a/A3')),
    meta: {}
}];
export default aRoutes;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

App.jsx

jsx
import React from "react";
import { HashRouter } from 'react-router-dom';
import HomeHead from './components/HomeHead';
import RouterView from "./router";

const App = function App() {
    return <HashRouter>
        <HomeHead />

        <div className="content">
            <RouterView />
        </div>
    </HashRouter>;
};

export default App;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
沪ICP备20006251号-1