reactjs - 动态加载惰性路由
问题描述
我有一个反应应用程序,其中用户导航/组件来自后端作为数组并存储在本地存储中。
示例导航属性;
{
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
,我看到图片中的路线,可能是因为`动态路线被渲染为数组?
解决方案
问题是关于webpack动态加载,不能将import url作为一个整体参数传递,必须先添加一个已有的前缀;
不工作
const fileUrl = "path/to/file";
lazy(() => import(fileUrl))
在职的
lazy(() => import("./path/to/" + filePath))
关于问题
推荐阅读
- paypal - Verify that mobile phone number is accociated with an active PayPal account
- java - Lucene Mmap 增加驻留内存
- java - java.lang.NoSuchFieldError: IMPORT_BEAN_NAME_GENERATOR
- group-by - 如何在 Microsoft Power Automate 中对 SharePoint 列表记录进行分组?
- hbase - Apache phoenix 的 order by 和 offset 问题在分页中给出重复的结果
- ios - 如何以编程方式快速获取关联域权利列表?
- ionic-framework - Ionic Appflow 动态 CHANNEL_NAME
- apache - 如何重定向 url htacces mod_rewrite?
- javascript - 让 div 上下滚动
- python - 将列表参数传递给 zeep 方法