首页 > 解决方案 > 如何更改 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>

有人知道怎么做吗?

标签: reactjsreact-routerreact-router-dom

解决方案


Switch 如果我理解您的问题/问题,您希望应用程序在不呈现“/main/messages ”时从“/main/messages”重定向到“/main/access/deny Route”。

解决方案

映射后的路由包含一个特定路径Redirect重定向另一路径的组件。如果它存在,则允许首先匹配for “/main/messages”,否则由于该路由不可用,因此将处理它。SwitchRouteRedirect

重定向自

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

推荐阅读