首页 > 解决方案 > ReactJS 动态路由

问题描述

我一直在使用 CoreUI 来更深入地学习 React。在一个名为“containers”的文件夹中,有一段代码似乎在遍历包含所有路由的文件。

<main className="main">
            <AppBreadcrumb appRoutes={routes}/>
            <Container fluid>
              <Switch>
              {routes.map((route, idx) => {
                  return route.component ? (<Route key={idx} path={route.path} exact={route.exact} name={route.name} render={props => (
                      <route.component {...props} />
                    )} />)
                    : (null);
                },
              )}
                <Redirect from="/" to="/dashboard" />
              </Switch>
            </Container>
          </main>

下面是 routes.js 文件的一个简短示例:

    const routes = [
  { path: '/', exact: true, name: 'Home', component: DefaultLayout },
  { path: '/dashboard', name: 'Dashboard', component: Dashboard },
  { path: '/theme', exact: true, name: 'Theme', component: Colors },

据我了解,代码正在尝试检查路径并仅根据浏览器的路径呈现组件,这是正确的吗?你能用普通的 IF-Else 范式解码上面的代码吗?

标签: reactjs

解决方案


你能用普通的 IF-Else 范式解码上面的代码吗?

要回答您的问题,您必须了解三元或条件运算符是什么。简而言之,它通过验证一个条件(在询问标记之前)来替换 if/else 语句,如果为真,它将执行询问标记旁边的任何操作,如果为假,它将执行冒号旁边的任何操作。所以:

condition ? do if true : do if false.

在这里查看更精确的定义。

普通版

return route.component ? (<Route key={idx} path={route.path} exact={route.exact} name={route.name} render={props => (
                  <route.component {...props} />
                )} />)
                : (null);

如果/其他版本

if (route.component){
    return (
        <Route key={idx} 
            path={route.path} 
            exact={route.exact} 
            name={route.name} 
            render={props => (<route.component {...props} />)} 
        />);
} else {
    return null;
}

所以,对于你的问题:

据我了解,代码正在尝试检查路径并仅根据浏览器的路径呈现组件

仅当在component名为routes. 如果该属性未在对象中设置,它将不会呈现任何内容(在 React 中,您可以通过返回 null 来做到这一点)。

Route 组件将根据浏览器的路径处理组件的渲染,并将其与示例中的“/”、“/dashboard”或“/themes”中path的项目的属性进行比较。routes


推荐阅读