简体   繁体   中英

How can I avoid duplication name in react-router-dom?

I have a user profile page component and in that page I have list of friends.

When I click on friend icon I route to friend page which use the same profile page component just render different info which get by id.

I did routes but if I will pass a few time to different friends I have the url like " user/user/user/1 ".

So if I route one time I have /user/1 and if I route one more time to another user I expected the link to be user/2 but I have user/user/2 . How can I fix this issue?

Link that routes to the user is inside a return of map function:

{friends.map((friendInfo, id) => 
  return(
    <Link to={`user/${friends.id}`} >
    </Link>
   );
})}

Routes

    <Route path="/" exact component={Profile} />
    <Route path="/user/:id" component={Profile} />

Here is what you can do to achieve your desired functionality: At first you can check if URl contains /user then don,t route to user and else go to /user . You can use withRouter or params to make get URl values.

For Example:

{friends.map((friendInfo, id) => 
  return(
    <Link to={url.includes('user')?`/${friends.id}`: `user/${friends.id}`} > 
     //do conditional rendering above to Link
    </Link>
   );
})}

In the render of friends array you should add back slash to your Link url

{friends.map((friendInfo, id) => 
  return(
    <Link to={`/user/${friends.id}`} > {/* <--- here add back slash */}
    </Link>
   );
})}

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