笔记二十六、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;
相关推荐
一壶纱5 分钟前
uni-app 使用 uview-plus
前端
敲敲了个代码7 分钟前
从零实现一个「就地编辑」组件:深入理解 OOP 封装与复用的艺术
前端·javascript·学习·面试·前端框架
xiechao8 分钟前
函数组件 useEffect 清理函数抛错:ErrorBoundary 能捕获吗?
前端·react.js
YJlio8 分钟前
Autologon 学习笔记(9.16):无感登录的正确打开方式(原理、风险与替代方案)
数据库·笔记·学习
♛小小小让让10 分钟前
FourCC、编解码器、 文件后缀、视频容器的关系
笔记·音视频
南游11 分钟前
数组判断?我早不用instanceof了,现在一行代码搞定!
前端·javascript
mouseliu14 分钟前
pnpm approve-builds报错
前端
JIseven15 分钟前
app页面-锚点滚动 和 滚动自动激活菜单
前端·javascript·html
AAA阿giao21 分钟前
在你的网页中嵌入 Coze 智能客服:一步步打造专属 AI Agent
前端·javascript·人工智能
AAA阿giao22 分钟前
深入解析 OOP 考题之 EditInPlace 类:从零开始掌握面向对象编程实战
前端·javascript·dom