简体   繁体   English

React router:如何在构建Links时处理trailing / in match.url?

[英]React router: How to handle trailing / in match.url when building Links?

I've been building Links in my React app (using react-router-dom 4.3.1) using code like the following: 我一直在使用如下代码在我的React应用程序(使用react-router-dom 4.3.1)中构建Links:

const { match } = this.props;
...
pages.map(page =>
    <Link to={match.url+'/'+page.id()+'/info'}>
        Go to info page for {page.title()}
    </Link>)

as this seems to be the recommended practice (eg see ${match.url}/components https://reacttraining.com/react-router/web/guides/quick-start/example-nested-routing ). 因为这似乎是推荐的做法(例如参见${match.url}/components https://reacttraining.com/react-router/web/guides/quick-start/example-nested-routing )。

The problem I'm having: 我遇到的问题:

If I'm at the following path: 如果我在以下路径:

/app/home

the links generated by the above are as expected: 上面生成的链接符合预期:

  • /app/home/1/info /应用/主页/ 1 /资讯
  • /app/home/2/info /应用/主页/ 2 /信息
  • /app/home/3/info /应用/家用/ 3 /信息
  • etc. 等等

But if I load this (subtlely different) path (notice the trailing /): 但是,如果我加载这个(微妙的不同)路径(注意尾随/):

/app/home/

then the generated links are wrong (notice the double / after home): 然后生成的链接是错误的(注意双/后回家):

  • /app/home//1/info /应用/家// 1 /信息
  • /app/home//2/info /应用/家// 2 /信息
  • /app/home//3/info /应用/家// 3 /信息
  • etc. 等等

In other words, the problem is that sometimes there's a trailing / and sometimes there is not. 换句话说,问题是有时会有尾随/有时没有。

When I'm building a link, do I need to manually check for a trailing / every time and strip it if it's there? 当我建立一个链接时,我是否需要手动检查尾随/每次并删除它是否存在? Or is there some better best practice that I'm perhaps missing? 或者是否有一些我可能缺少的更好的最佳实践?

Discard a trailing / provided by the user: 丢弃用户的尾随/提供:

const {match} = this.props;
let len = match.url.length;
match.url = (match.url[len - 1] === "/") ? match.url.substring(0, len-1) : match.url;

...

pages.map(page =>
<Link to={match.url+'/'+page.id()+'/info'}>
    Go to info page for {page.title()}
</Link>)

Alternately you can add if its missing as well: 或者你也可以添加它的缺失:

match.url = (match.url[len - 1] === "/") ? match.url : match.url + "/";

pages....
    <Link to={match.url + page.id() ....}
... 

I think it's easier to add a missing one rather than discarding an existing one. 我认为添加一个丢失的而不是丢弃现有的更容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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