reactjs - 将所有路由重定向到一个页面
问题描述
我有很多这样的路线
<Switch>
<Route path="/dashboard" component={Dashboard} key="dashboard" />
<Route path="/projects" component={UserProjects} key="userprojects" />
<Route path="/compute/servers" component={ProjectServerList} key="projectserverlist" />
<Route path="/compute/snapshots" component={ServerSnapshotList} key="ServerSnapshotList" />
<Route path="/compute/keypairs" component={KeypairList} key="KeypairList" />
它们工作正常,但如果未设置属性,我希望将它们全部重定向到“/dashboard”
我试过这个:
{myproperty ?
<Switch>
<Route path="/dashboard" component={Dashboard} key="dashboard" />
</Switch>
:
<Switch>
<Route path="/dashboard" component={Dashboard} key="dashboard" />
<Route path="/projects" component={UserProjects} key="userprojects" />
<Route path="/compute/servers" component={ProjectServerList} key="projectserverlist" />
<Route path="/compute/snapshots" component={ServerSnapshotList} key="ServerSnapshotList" />
<Route path="/compute/keypairs" component={KeypairList} key="KeypairList" />
</Switch>
}
并且错误地失败了
我正在使用“react-router-dom”:“^4.3.1”,“react-router-redux”:“^5.0.0-alpha.9”,“react”:“^16.13.1”,
解决方案
简单、干净、可重复使用——
如果该属性不存在,则创建一个重定向到仪表板(或指定的任何路径)的组件,否则它会呈现路由本身。
export const ProtectedRoute = ({comp: Component, redirectTo, path, key}) => {
const propertyExists = "...";
if (propertyExists) return <Route path={path} component={Component} key={key}></Route>;
else return <Redirect to={redirectTo || "/dashboard"}/>
};
现在在路线内
<Switch>
<Route path="/dashboard" component={Dashboard} key="dashboard" />
<ProtectedRoute path="/projects" component={UserProjects} key="userprojects" />
<ProtectedRoute path="/compute/servers" component={ProjectServerList} key="projectserverlist" />
<ProtectedRoute path="/compute/snapshots" component={ServerSnapshotList} key="ServerSnapshotList" />
<ProtectedRoute path="/compute/keypairs" component={KeypairList} key="KeypairList" />
推荐阅读
- javascript - parsing JSON data returns undefined
- java - java.lang.IllegalStateException:没有包含点,Crash APP
- r - 如何根据不同列中的值替换数据框中的值
- c# - 无法在通用父基类中接口的显式实现中将子类显式转换为另一个子类
- python - 我很难使用 os.rename 批量重命名文件
- excel - Count special characters in range in a function
- odoo - 基于 res.users 中字段的域过滤器,用于 Odoo XML 树视图
- android - 如何禁用 ColumnHeader 和 RowHeader 并禁用 SelectedColor
- ip - 如何在拆分隧道 VPN 上确定我的 IP 地址?
- hibernate - 从多对一/一对多映射中获取数据