我一直在使用CoreUI来学习更深入的反应。在一个名为"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-否则范式来解码上面的代码吗?
发布于 2018-09-04 18:55:11
你能用一个正常的IF-否则范式来解码上面的代码吗?
要回答您的问题,您必须了解三元运算符或条件运算符是什么。简而言之,它通过验证一个条件(在询问标记之前)替换if/else语句,如果是true,它将执行询问标记旁边的任何操作,如果false将执行冒号旁边的任何操作。所以:
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/else版本
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来完成此操作)。
路由组件将根据浏览器的路径处理组件的呈现,并将其与示例中的“/”、“/仪表板”或“/ routes
”中的项的routes
属性进行比较。
https://stackoverflow.com/questions/52167674
复制相似问题