简体   繁体   中英

How to change URL path in react-router-dom?

I use several route in my app And I have conditions for bringing information in that route. I created an array and the array values are created according to those conditions. Part of my code:

  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}/>})
                  }
               }

and:

   <Switch>
     {this.state.routearray ?this.state.routearray.map(item=>{
return <Route path={item.path}>{item.component}</Route>
   </Switch>   

In this case, for example, I have access to the Route of the message when the MsgManagementTab exists. What I want to do is if the MsgManagementTab does not exist, and if the user wants to go to the page via URL, go to the path I want to be redirected to. This is the path I want to redirected:

 <Route path="/main/access/deny"><NoAccess  isSidebarActive={this.state.isSidebarActive} /></Route>

Someone knows how to do this?

If I understand your question/issue, you want the app to redirect from "/main/messages" to "/main/access/deny" when the Switch isn't rendering the Route for "/main/messages".

Solution

After the mapped routes include a Redirect component to redirect from a specific path to another path. This works by allowing the Switch to match the Route for "/main/messages" first if it exists, otherwise since that route won't be available the Redirect will handle it.

Redirect from

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM