首页 > 解决方案 > 动态加载惰性路由

问题描述

我有一个反应应用程序,其中用户导航/组件来自后端作为数组并存储在本地存储中。

示例导航属性;

{
    component: "dashboard",
    fileUrl: "./views/dashboard/analytics/AnalyticsDashboard",
    icon: "Home",
    id: 1,
    name: "view",
    type: "item",
    url: "dashboard",
}

所有组件都使用延迟加载功能包装。所以,我尝试的是;

惰性组件数组

import userNavigation from './configs/userNavigation'

const lazyComponents = userNavigation.reduce(function (result, item) {
  var key = item.component;
  result[key] = lazy(() => import(`'${item.fileUrl}'`));
  return result;
}, {});

AppRouter 组件渲染

render() {
    
    const dynamicRoutes = userNavigation.map(({id, url, component}) => 
        <RouteConfig key={id} path={url} component={lazyComps[component]}></RouteConfig>  
    )

    return (
      <Router history={history}>
        <Switch>
          <RouteConfig exact path="/" component={Landing} fullLayout />
          {dynamicRoutes}
          <RouteConfig path="/login" component={Login} fullLayout />
          <RouteConfig path="/register" component={register} fullLayout />
          <RouteConfig component={error404} fullLayout />
        </Switch>
      </Router>
    )
  }

RouterConfig 是 Route 的包装组件,用于配置;

const RouteConfig = ({ component: Component, fullLayout, ...rest }) => (
  <Route
    {...rest}
    render={props => {
      return (
        <ContextLayout.Consumer>
          {context => {
            let LayoutTag =
              fullLayout === true
                ? context.fullLayout
                : context.state.activeLayout === "horizontal"
                  ? context.horizontalLayout
                  : context.VerticalLayout
            return (
              <LayoutTag {...props} >
                <Suspense fallback={<Spinner />}>
                  <Component {...props} />
                </Suspense>
              </LayoutTag>
            )
          }}
        </ContextLayout.Consumer>
      )
    }}
  />
)

所以问题是渲染了动态路由,但它们不起作用。我可以看到所有路线。/login./register路线工作正常,但动态呈现的路线是回退到/error404. 顺便说一句,当我检查时Switch,我看到图片中的路线,可能是因为`动态路线被渲染为数组?

在此处输入图像描述

标签: reactjsreact-router

解决方案


问题是关于webpack动态加载,不能将import url作为一个整体参数传递,必须先添加一个已有的前缀;

不工作

const fileUrl = "path/to/file";
lazy(() => import(fileUrl))

在职的

lazy(() => import("./path/to/" + filePath))

关于问题


推荐阅读