【问题标题】:Loading lazy routes dynamically动态加载惰性路由
【发布时间】:2020-07-28 14:30:48
【问题描述】:

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

示例导航属性;

{
    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 时,我看到了图片中的路由,可能是因为`动态路由被渲染为数组?

【问题讨论】:

    标签: reactjs react-router


    【解决方案1】:

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

    不工作

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

    工作

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

    关于issue

    【讨论】:

      猜你喜欢
      • 2019-10-27
      • 2020-09-22
      • 1970-01-01
      • 2013-05-22
      • 1970-01-01
      • 2019-11-22
      • 1970-01-01
      • 1970-01-01
      • 2019-03-28
      相关资源
      最近更新 更多