reactjs 动态路由 动态导入组件 require和react-loadable 传入变量

本文介绍了在React应用中如何根据后端返回的数据动态导入组件,分别使用了require和react-loadable两种方法。require方法直接在代码中拼接字符串来动态导入组件,而react-loadable则利用懒加载实现动态导入,提高应用性能。这两种方法都可以解决在未知组件路径情况下生成动态路由的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.常规导入组件

常规的导入组件需要在文件开始就将导入的组件写死,如下

import xxx from 'xxx'

现在我需要通过后端返回的数组动态的生成路由,因此在不知道后端返回的情况下,不知道需要导入哪些组件,就需要根据后端返回的组件路径,动态导入组件,

方法一:require

后端返回的数据如下:

[{
    path: '/login',
    component: 'Login'
}]

可以看见,组件为一个字符串路径。
routes.js如下:

/**
 * 根据数组生成路由数组,主要是根据routeArys中组件的路径动态的导入组件
 * @param {后端返回的路由数组} routeArys 
 */
const createRoutesByRequire = (routeArys) => {
   
    return routeArys.map(routeObj => {

            if (routeObj.children) {
                return ({
                    ...routeObj,
                    component: require(`../pages/${routeObj.component}`).default, // 注意不要在require中全部写变量,需要拼接
                    children: createRoutesByRequire(routeObj.children)
                })
            }else {
                return ({
                    ...routeObj,
                    component: require(`../pages/${routeObj.component}`).default // 注意不要在require中全部写变量,需要拼接
                })
            }
            
        });
    
}


/**
 * 导出路由数组
 */
export const mainRoutes = createRoutesByRequire([{
    path: '/login',
    component: 'Login'
}])

index.js如下:

import ReactDOM from 'react-dom';
import './index.css';
import reportWebVitals from './reportWebVitals';
import { HashRouter as Router, Switch, Route, Redirect } from "react-router-dom";
import { mainRoutes } from './routes'; //导入routes.js中的mainRoutes

ReactDOM.render(
<Router>
  <Switch>
    {mainRoutes.map(route => {
        return <Route key={route.path} {...route}/>;
      })}    
  </Switch>
</Router>,
document.getElementById('root')
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

方法二:react-loadable

首先需要安装 react-loadable

yarn add react-loadable

新建LoadableUtils.js如下:

import React from 'react';
import Loadable from 'react-loadable';

export default (loader) => {
    return Loadable({
        loader,
        loading() {
            return <div>正在加载...</div>
        }
    });
}

routes.js 如下:


import LoadableUtils from "../utils/LoadableUtils";

const createRoutesByReactLoadable = (routeArys) => {
   
    return routeArys.map(routeObj => {

            if (routeObj.children) {
                return ({
                    ...routeObj,
                    component: LoadableUtils(() => import(`../pages/${routeObj.component}`)), // 此处不要在import中全部传入变量,需要拼接
                    children: createRoutesByReactLoadable(routeObj.children)
                })
            }else {
                return ({
                    ...routeObj,
                    component: LoadableUtils(() => import(`../pages/${routeObj.component}`)) // 此处不要在import中全部传入变量,需要拼接
                })
            }
            
        });
    
}


/**
 * 导出路由数组
 */
export const mainRoutes = createRoutesByReactLoadable([{
    path: '/login',
    component: 'Login'
}])

index.js 如下:

import ReactDOM from 'react-dom';
import './index.css';
import reportWebVitals from './reportWebVitals';
import { HashRouter as Router, Switch, Route, Redirect } from "react-router-dom";
import { mainRoutes } from './routes'; //导入routes.js中的mainRoutes

ReactDOM.render(
<Router>
  <Switch>
    {mainRoutes.map(route => {
        return <Route key={route.path} {...route}/>;
      })}    
  </Switch>
</Router>,
document.getElementById('root')
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

本文参考:https://blog.youkuaiyun.com/noperfecttttt/article/details/81557845

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值