笔记二十六、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;
相关推荐
预知同行2 分钟前
从 MCP 到 CLI:AI Agent 工具链的架构演进与实战抉择
前端·面试
何智超4 分钟前
AI 微前端性能优化之旅(中):重启
前端·vibecoding
xian_wwq4 分钟前
【学习笔记】Prompt Engineering 没死,只是它不再够用了-2/16
笔记·学习·prompt
渣波5 分钟前
拒绝 Redux 样板代码:Zustand 核心原理与实战进阶指南(基础、异步与切片模式)
前端·javascript
Hamm31 分钟前
前端转Java+AI全栈?那我推荐几个实战开源项目给你
前端·后端·全栈
饼干哥哥40 分钟前
十年数据分析经验,被我打包成了4个跨境VOC Skill
前端·数据分析·数据可视化
东方小月1 小时前
从零开发一个 Coding Agent(六):实现一个可脚本化的 Faux Provider
前端·人工智能
程序员黑豆1 小时前
什么是JDK以及JDK都由哪些部分组成呢
java·前端·ai编程
210Brian1 小时前
STM32学习笔记(五)EXTI外部中断(上)
笔记·stm32·学习
妙码生花1 小时前
让各大 AI 整理出来的前端工程命名最简实践(Vue + TS)
前端·javascript·vue.js