有条件的渲染映射的路线[回答]

时间:2019-07-08 05:05:23

标签: reactjs react-router

我想在开关内进行条件渲染映射。

Routes.js

  <Switch>
    {routeConfig.isSecureRoute === true ? 
      {routeConfig.map((route) => (
        <SecureRoute key={route} {...route} />
      ))}
    :
      {routeConfig.map((route) => (
        <Route key={route} {...route} />
      ))}
    }
  </Switch>

routeConfig是对象数组,其值为isSecureRoute: true/false

routeConfig.js

const routeConfig = [
 {
   path: "/home",
   component: Home,
   exact: true,
   isSecureRoute: true
 },
 (...)
]

我遇到解析错误:

code_error_screenshot

不确定如何正确设置我的映射。请帮忙,谢谢高级!!此外,我还很陌生,因此非常感谢您提供详细的响应或代码示例:)

1 个答案:

答案 0 :(得分:0)

您应该这样做

<Switch>
    {routeConfig.map((route, index) => {
          return route.isSecureRoute === true ? (
            <Route key={index} {...route} />
          ) : (
            <Route key={index} {...route} />
          )
        })
    }
  </Switch>