笔记二十六、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;
相关推荐
json{shen:"jing"}16 分钟前
07_表单输入绑定
java·前端·javascript
yyt36304584130 分钟前
K 线图高性能窗口化渲染
前端·javascript·css·vue.js·gitee·vue
XiaoYu200236 分钟前
第5章 Nest.js精进-IOC控制反转
前端
LV技术派36 分钟前
适合很多公司和团队的 AI Coding 落地范式(二)
前端·aigc·ai编程
IT_陈寒37 分钟前
Redis性能翻倍的5个冷门技巧:从每秒10万到20万的实战优化之路
前端·人工智能·后端
ss27342 分钟前
高版本node启动RuoYi-Vue若依前端ruoyi-ui
前端·javascript·vue.js
饼干,1 小时前
模拟试卷2
前端·javascript·easyui
HXR_plume1 小时前
【Web信息处理与应用课程笔记4】个性化检索(下)
笔记
im_AMBER1 小时前
Leetcode 94 合并零之间的节点
数据结构·c++·笔记·学习·算法·leetcode
南雨北斗1 小时前
js 严格模式
前端