首页 > 解决方案 > 将所有路由重定向到一个页面

问题描述

我有很多这样的路线

<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”,

标签: reactjsreact-router-domreact-router-v4react-router-redux

解决方案


简单、干净、可重复使用——

如果该属性不存在,则创建一个重定向到仪表板(或指定的任何路径)的组件,否则它会呈现路由本身。


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" />

推荐阅读