笔记二十六、React中路由懒加载的扩展使用

26.1 在路由中配置懒加载 lazy

routes/index.jsx

代码

javascript 复制代码
import {Navigate} from "react-router-dom";
import Home from "../components/Home";
import About from "../components/About";
// import Classify from "../components/Home/components/Classify.jsx";
// import Navigation from "../components/Home/components/Navigation.jsx";
import {lazy} from "react";

//动态引入路径传入lazy函数
const Classify = lazy(() => import("../components/Home/components/Classify"));
const Navigation = lazy(() => import("../components/Home/components/Navigation"));

export default [
    {
        path: '/home',
        element: <Home/>,
        children: [
            {
                path: 'classify',
                element: <Classify/>
            },
            {
                path: 'navigation',
                element: <Navigation/>
            },
        ]
    },
    {
        path: '/about',
        element: <About/>,
    },
    {
        path: '/',
        element: <Navigate to='about'/>,
    }
]

26.2 Home/index.jsx 在父组件中使用 Suspense

代码

javascript 复制代码
import React, {Suspense} from "react";
import {NavLink, Outlet, useNavigate} from "react-router-dom";

const Home = () => {

    // 类组件中不能用const定义变量
    // 选中高亮
    const activeStyle = ({isActive}) => {
        return isActive ? 'background' : "";
    };

    // 编程式路由导航
    const navigate = useNavigate();
    const toClassify = () => {
        navigate('classify', {state: {param_C: 'elendalee', param_D: 20}})
    };

    return (
        <div>
            首页的页面
            <div style={{display: "flex", justifyContent: 'center', marginTop: '20px'}}>
                <button onClick={toClassify}>classify</button>
                <NavLink to='navigation' className={activeStyle}>navigation</NavLink>
            </div>
            <div style={{background: 'red'}}>
                {/*fallback 兜底样式loading...*/}
                <Suspense fallback={<h2>loading...</h2>}>
                    {/*<!-- Renders the child route's element, if there is one. -->*/}
                    <Outlet/>
                </Suspense>
            </div>
        </div>);

}

export default Home;
相关推荐
全栈技术负责人21 分钟前
Claw Code 系统架构与 Agent 运行机制解析
前端·系统架构·ai编程
人人常欢笑21 分钟前
Grafana 表格自定义下载样式。
javascript·react.js·grafana
x-cmd25 分钟前
[x-cmd] 专为 AI Agent 设计的无头浏览器,比 Chrome 速度快 9 倍且少用 16 倍内存 | Lightpanda
前端·chrome·ai·自动化·agent·浏览器·x-cmd
chxii36 分钟前
Nginx 正则 location 指令匹配客户端请求的 URI
前端·nginx
qing2222222238 分钟前
Linux:/var/log/journal 路径下文件不断增加导致根目录磁盘爆满
linux·运维·前端
Armouy43 分钟前
Nuxt.js 学习复盘:核心概念与实战要点
前端·javascript·学习
ZhaoJuFei1 小时前
React生态学习路线
前端·学习·react.js
早點睡3901 小时前
ReactNative项目OpenHarmony三方库集成实战:react-native-calendar-events(读取不到日历里新增的事件,待排查)
javascript·react native·react.js
apcipot_rain1 小时前
CSS知识概述
前端·css
837927397@QQ.COM1 小时前
个人理解无界原理
开发语言·前端·javascript