reactjs - 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 范式解码上面的代码吗?
解决方案
你能用普通的 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
推荐阅读
- python - 如何将 Pandas 数据框转换为单个列表
- microsoft-graph-api - Microsoft Graph 日历 CTAG/Changekey 未更改
- php - Laravel Eloquent 的条件 wherehas
- mysql - 在 MYSQL 中获取每个员工的每日先进后出时间
- python - Python 中的“Function()[x]”中的 [x] 是什么?
- r - 子集数据框以排除三列具有 NA 值的值
- javascript - Javascript 元素对象未引用 DOM 输入元素
- mongodb - MongoDB 查询 - 聚合和嵌入文档
- javascript - 角度传递子数据以查看
- image - 谷歌地图静态图片给了我错误的地图类型?