已有一个需要动态加载路由的需求,在v5版本中我是这样写的
// route , 简化案例只留下一级路由
const routes = {
name: '仪表盘',
key: 'dashboard',
},
// 动态写入component
routes.forEach((route) => {
route.component = lazyload(mod[`./pages/${route.key}/index.tsx`]);
});
<Switch>
{routes.map((route, index) => {
return (
<Route
key={index}
path={`/${route.key}`}
component={route.component}
/>
);
})}
<Switch>
赋值到compont上是属于组件类型的,也符合v5中<Route path="xxx" component={component}>
的写法
但当我升级到v6后,v6将component换成了element,element属于元素类型,改造之后会报 element不是元素的错误
<Routes>
{routes.map((route, index) => {
return (
<Route
key={index}
path={`/${route.key}`}
element={route.component}
/>
);
})}
<Switch>
包一层React.createElement就可以解决了