从对象数组中渲染组件

时间:2018-09-17 11:21:53

标签: javascript reactjs react-router

我有一个对象数组,其中包含另一个这样的对象数组:

[{label: "Commons",
  path: "commons",
  component: Commons,
  subroutes: [
  {
    label: "Commons doc",
    path: "commons/doc",
    component: CommonsDoc,
  }]
 }]

然后我将其作为道具传递给组件,并将其映射到React的第一级组件“ Commons”中,并在另一个块中进行渲染:

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

我正在使用Reach Router for React,现在我试图在子路由上使用第二个map函数在第一个<route.component path={route.path} key={index} />

下渲染第二级组件。

但是我无法像这样{route.subroutes.map(...)}那样在第二个对象数组中呈现CommonsDoc组件

3 个答案:

答案 0 :(得分:1)

如果我的问题正确,则应该这样映射它:

from scipy.spatial.distance import cKDTree X_cTree = cKDTree(X) Y_cTree = cKDTree(Y) D_coo = X_cTree.sparse_distance_matrix(Y_cTree, r = r, output_type = `coo_matrix`) r_i = D_coo.row r_j = D_coo.column r_d = D_coo.data

答案 1 :(得分:0)

要在JSX中创建动态标签名称,您需要将名称值分配给大写变量

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

您应该对子路由执行相同的操作

答案 2 :(得分:0)

类似的东西应该可以帮助您:

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>