Javascript 从对象数组渲染组件

Javascript 从对象数组渲染组件,javascript,reactjs,react-router,Javascript,Reactjs,React Router,我有一个对象数组,包含另一个对象数组,如下所示: [{label: "Commons", path: "commons", component: Commons, subroutes: [ { label: "Commons doc", path: "commons/doc", component: CommonsDoc, }] }] 然后我将其作为一个道具传递给一个组件,并将该道具映射到一级组件“Commons”中,并在另一个区域中使用该道具进行

我有一个对象数组,包含另一个对象数组,如下所示:

[{label: "Commons",
  path: "commons",
  component: Commons,
  subroutes: [
  {
    label: "Commons doc",
    path: "commons/doc",
    component: CommonsDoc,
  }]
 }]
然后我将其作为一个道具传递给一个组件,并将该道具映射到一级组件“Commons”中,并在另一个区域中使用该道具进行渲染:

<StyledRouter>
    {routes.map((route, index) => (
        <route.component path={route.path} key={index} />
    ))}
</StyledRouter>

{routes.map((路由,索引)=>(
))}
我正在使用React的Reach路由器,现在我正在尝试在子例程中渲染二级组件,使用第一个


但是我不能让它像这样工作,在我的第二个对象数组中呈现
commondoc
组件

如果我答对了问题,你应该这样映射它:


routes.map(route=>route.subroutes.map(subroute=>“对每个子例程执行任何操作”)

要在JSX中创建动态标记名,需要将名称值赋给大写的变量

<StyledRouter>
   {routes.map((route, index) => {
     const Route = route.component;
     return (<Route path={route.path} key={index} />)
   })}
</StyledRouter>

{routes.map((路由,索引)=>{
const Route=Route.component;
返回()
})}

您应该对子例程执行相同的操作,类似这样的操作应该会帮助您:

const composeRoutes = (routes) => {
    allRoutes = routes.map((route, index) => {
        if (route.subroutes.length > 0) {
            let withSubRoutes = [];
            withSubRoutes = composeRoutes(route.subroutes);
            withSubRoutes.append(<route.component path={route.path} key={index} />);
            return withSubRoutes;
        }
        return <route.component path={route.path} key={index} />;
    })
    return _.flatten(allRoutes);
};
<StyledRouter>
    {composeRoutes(routes)}
</StyledRouter>
const composer路由=(路由)=>{
allRoutes=routes.map((路由,索引)=>{
如果(route.subroutes.length>0){
让with subroutes=[];
withSubRoutes=复合路由(路由.子路由);
withSubRoutes.append();
返回地铁;
}
返回;
})
返回展平(所有路线);
};
{路由(路由)}

不,我不想直接访问子例程。。。我需要从数组中的“第一级”渲染组件,然后访问第二级(子例程)从中渲染组件如果我是正确的,这并不能真正解决我的问题?这只是写它的另一种方式,我已经可以在第一个贴图中渲染了,这是我的第一个ObjectSome数组的组件!对于任何有类似问题的人,它都进行了一些修改:因为我没有使用Lodash
\uuz.flatte(allRoutes)变成了
allRoutes.flat()
并且错误告诉我
.append
不是一个函数,所以它变成了
.push