reactjs - 如何更改 react-router-dom 中的 URL 路径?
问题描述
我在我的应用程序中使用了几条路线并且我有条件在该路线中引入信息。我创建了一个数组,并根据这些条件创建了数组值。我的部分代码:
for (var i = 0; i < res.length; i++){
var arr = res[i];
switch (arr) {
case "MsgManagementTab":
routearray.push({path :"/main/messages" ,component:<Messages isSidebarActive={this.state.isSidebarActive} />})
break;
case "AlgorithmManagementTab":
routearray.push({path :"/main/algorithms",component:<Algorithm isSidebarActive={this.state.isSidebarActive}/>})
break;
case "SocialNetworkManagementTab":
routearray.push({path :"/main/socialNetworks",component:<SocialNetWork isSidebarActive={this.state.isSidebarActive}/>})
}
}
和 :
<Switch>
{this.state.routearray ?this.state.routearray.map(item=>{
return <Route path={item.path}>{item.component}</Route>
</Switch>
在这种情况下,例如,当MsgManagementTab
存在时,我可以访问消息的 Route。我想要做的是如果MsgManagementTab
不存在,并且如果用户想通过 URL 访问该页面,请转到我想要重定向到的路径。这是我要重定向的路径:
<Route path="/main/access/deny"><NoAccess isSidebarActive={this.state.isSidebarActive} /></Route>
有人知道怎么做吗?
解决方案
Switch
如果我理解您的问题/问题,您希望应用程序在不呈现“/main/messages ”时从“/main/messages”重定向到“/main/access/deny Route
”。
解决方案
映射后的路由包含一个从特定路径Redirect
重定向到另一路径的组件。如果它存在,则允许首先匹配for “/main/messages”,否则由于该路由不可用,因此将处理它。Switch
Route
Redirect
<Switch>
...
{this.state.routearray ? this.state.routearray.map(item => (
<Route path={item.path}>{item.component}</Route>
))}
...
<Redirect from="/main/messages" to="/main/access/deny />
...
<Route path="/main/access/deny">
<NoAccess isSidebarActive={this.state.isSidebarActive} />
</Route>
...
</Switch>
推荐阅读
- javascript - 如何让作者角色在 Strapi 仪表板上发布内容?
- r - 如何自动生成函数中的组比较以用于 stat_compare_mean?
- python - 用户名/密码登录系统 - 检查用户名与密码的相关性
- python - 如何检查 2 个 Pandas Series 对象的相等性?
- github - 了解 GitHub 分支 - 使用哪个分支提交到 App Store?
- nginx - Docker swarm - 如何确保服务在更新时正确链接
- javascript - 传单 - 删除/重播覆盖控制框
- python - Tkinter 树视图在 (0,0) 上添加额外空间
- javascript - 使用导入命令时出现意外的令牌错误
- django - 如何在 Q 对象中使用相关名称字段