【发布时间】: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