【问题标题】:How to run nested map in Reactjs?如何在 Reactjs 中运行嵌套地图?
【发布时间】:2020-09-11 17:07:41
【问题描述】:

如何使用 map 函数返回不同的组件。如何在地图函数中应用条件

我试图返回一个组件,如果subMain 为真,则返回该部分组件,如果subMain 为假,则返回该部分组件。

但这里只是结构中的错误。错误显示在这里!subMain

更新:我尝试了另一种方法,但这会在第二次返回和 const MainPath 中引发错误

            {states &&            
            states.map(({ Main }) => (
                Main.map(({component , subMain}) => (
                    const MainPath = `/${component}`
                    const MainComponent = `${component}`
                    subMain ? subMain.map(({ component }) => {
                        
                            const Path = `/${component}`
                            const Component = `${component}`
                            return (
                                <Protected
                                path={Path}
                                component={Component}
                                exact
                            />
                            )
                        }):
                            return (
                                <Protected
                                path={MenuPath}
                                component={MenuComponent}
                                exact
                            />
                            )
                                                    
                ))
            ))
        }

【问题讨论】:

  • 你的 subMain 不是布尔值!

标签: reactjs


【解决方案1】:

编辑:更新问题后,我认为只有一些语法错误和缺少返回语句

您正在运行 2 个表达式,而不仅仅是一个返回值。你应该像这样使用三元组

  {states &&            
        states.map(({ Main }) => (
            Main.map(({component , subMain}) => {
                const MainPath = `/${component}`
                const MainComponent = `${component}`
                return subMain ? subMain.map(({ component }) => {
                    
                        const Path = `/${component}`
                        const Component = `${component}`
                        return (
                            <Protected
                            path={Path}
                            component={Component}
                            exact
                        />
                        )
                    }):
                  (
                      <Protected
                         path={MenuPath}
                         component={MenuComponent}
                         exact
                      />
                  )
                                                
            })
        ))
    }

【讨论】:

  • 使用它连续运行它不会停止
  • 嗯,您正在循环遍历状态,然后是 Main.Map,然后可能又是 Main.Map - 有点问题,但与核心问题无关......尽管我不知道,但仍然不应该永远不知道数据是什么样子的
  • 我尝试了另一种方法并更新了问题,但它引发了错误
  • @Akhi21 You're new way is missing 'rerun on line 6 return subMain ? .. 你只能在返回所有代码时省略返回...
  • 那么我需要把整个内容都包装在 return 里面吗?
猜你喜欢
  • 2020-01-04
  • 2020-08-30
  • 2022-12-09
  • 1970-01-01
  • 1970-01-01
  • 2017-02-24
  • 1970-01-01
  • 2017-05-23
  • 2016-09-15
相关资源
最近更新 更多