代码之家  ›  专栏  ›  技术社区  ›  Tom G

反应路由器:如何处理拖尾/入匹配.url建立链接时?

  •  0
  • Tom G  · 技术社区  · 6 年前

    我一直在使用如下代码在React应用程序(使用React router dom 4.3.1)中构建链接:

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

    因为这似乎是推荐的做法(例如,参见 ${match.url}/components https://reacttraining.com/react-router/web/guides/quick-start/example-nested-routing ).

    如果我在以下路径:

    /app/home
    

    上述生成的链接如预期所示:

    • /应用程序/主页/2/信息
    • /应用程序/主页/3/info
    • 等。

    但是如果我加载这个(略有不同)路径(注意后面的/):

    /app/home/
    

    那么生成的链接是错误的(注意double/after home):

    • /app/home//3/信息
    • 等。

    当我建立一个链接时,我是否需要手动检查是否有尾随/每一次并删除它(如果有)?或者有没有更好的最佳实践,我可能会错过?

    0 回复  |  直到 6 年前
        1
  •  1
  •   Dblaze47    6 年前

    / 用户提供:

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

    或者,如果您可以添加缺失:

    match.url = (match.url[len - 1] === "/") ? match.url : match.url + "/";
    
    pages....
        <Link to={match.url + page.id() ....}
    ... 
    

    推荐文章