【问题标题】:Render components from an array of object从对象数组渲染组件
【发布时间】:2018-09-17 11:21:52
【问题描述】:

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

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

然后我将它作为一个 prop 传递给一个组件,并将该 prop 映射到 React 第一级组件 "Commons" 中,并在另一个 bloc 中使用它:

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

我正在为 React 使用 Reach Router,现在我正在尝试使用第一个 &lt;route.component path={route.path} key={index} /&gt; 正下方的第二个 map 函数在子路由处渲染第二级组件

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

【问题讨论】:

    标签: javascript reactjs react-router


    【解决方案1】:

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

    routes.map(route =&gt; route.subroutes).map(subroute =&gt; 'do whatever you want with each subroute')

    【讨论】:

    • 不,我不想直接访问子路由......我需要从我的数组中渲染“第一级”组件,然后访问第二级(子路由)以从那里渲染组件
    【解决方案2】:

    这样的事情应该可以帮助你:

    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>
    

    【讨论】:

    • 太棒了!对于遇到类似问题的任何人,它都进行了一些修改:因为我没有使用 Lodash _.flatten(allRoutes); 变成了 allRoutes.flat() 并且错误告诉我 .append 不是一个函数,所以它变成了 .push
    【解决方案3】:

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

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

    你应该对子路由做同样的事情

    【讨论】:

    • 如果我是对的,这并不能真正解决我遇到的问题吗?这只是另一种写法,我已经可以在第一个地图中渲染,这是我的第一个对象数组的组件
    猜你喜欢
    • 2015-11-16
    • 2018-11-29
    • 2019-11-15
    • 2019-04-23
    • 1970-01-01
    • 2021-12-26
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多