笔记二十六、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;
相关推荐
谈不譚网安8 分钟前
CSRF请求伪造
前端·网络安全·csrf
帅云毅11 分钟前
Web3.0的认知补充(去中心化)
笔记·学习·web3·去中心化·区块链
豆豆12 分钟前
day32 学习笔记
图像处理·笔记·opencv·学习·计算机视觉
TT模板13 分钟前
苹果cmsV10主题 MXonePro二开优化修复开源版
前端·html5
拖孩14 分钟前
【Nova UI】十一、组件库中 Icon 组件的测试、使用与全局注册全攻略
前端·javascript·vue.js·ui·sass
去伪存真20 分钟前
不用动脑,手把手跟着我做,就能掌握Gitlab+Jenkins提交代码自动构部署
前端·jenkins
nenchoumi311933 分钟前
VLA 论文精读(十六)FP3: A 3D Foundation Policy for Robotic Manipulation
论文阅读·人工智能·笔记·学习·vln
凉、介39 分钟前
PCI 总线学习笔记(五)
android·linux·笔记·学习·pcie·pci
天天扭码1 小时前
深入解析 JavaScript 中的每一类函数:从语法到对比,全面掌握适用场景
前端·javascript·面试
小希爸爸1 小时前
4、中医基础入门和养生
前端·后端