笔记二十六、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;
相关推荐
起这个名字4 分钟前
Typescript 装饰器执行顺序
前端
LDX前端校草5 分钟前
position属性值及用法
前端·javascript·面试
Bigfish_coding10 分钟前
前端转agent-第一周【python】-05 Ollama+Qwen3实战:会话记忆实战
前端
x***r15111 分钟前
.NET 10 SDK 安装教程(dotnet-sdk-10.0.100-win-x64详细步骤)
java·服务器·前端
新新技术迷12 分钟前
给 Agent 做"工具调用过程可视化",让用户看见它在干嘛
前端
feixing_fx19 分钟前
选择器的威力——深入理解优先级计算与层叠规则
开发语言·前端·css·前端框架·html
代码小库23 分钟前
【2026前端转 AI 全栈指南】第 1 章:前言 · 后端架构 · 章节导览
前端·人工智能·架构
晓131325 分钟前
【Cocos Creator 3.x】篇——第四章 子系统
前端·javascript·游戏引擎
Ab_stupid27 分钟前
CTF-Crypto培训笔记-现代密码
笔记·des·aes·rsa·crypto
ikoala33 分钟前
Codex 怎么买、怎么充值?先把这两套计费搞清楚
前端·javascript·后端