【问题标题】:How Can I Have Optional *Non*-Parameter URL Parts?我怎样才能拥有可选的 *Non*-Parameter URL 部分?
【发布时间】:2018-01-17 21:16:37
【问题描述】:

This Stack Overflow question/answer 解释了如何定义包含多个可选参数的 React Router (v4) 路由,例如:

<Route path="/to/page/:pathParam1?/:pathParam2?" component={MyPage} />

但是,它没有解释如何在这些参数之间放置可选文本,例如:

<Route path="/to/page/:pathParam1?/otherParam/:pathParam2?" component={MyPage} />
// Should match /to/page/1 AND /to/page/1/otherParam/2

这在以前版本的 React Router 中当然是可能的,但我看不到在当前版本中如何做到这一点。有没有办法指定可选的参数/非参数配对,甚至只是可选的非参数?比如:

<Route path="/to/page/:pathParam1?/(otherParam/:pathParam2?)" component={MyPage} />

【问题讨论】:

    标签: reactjs react-router react-router-v4


    【解决方案1】:

    React 路由器使用 path-to-regexp - https://github.com/pillarjs/path-to-regexp

    你可以用这样的路径匹配可选的非参数:

    const path = "/to/page/:pathParam1?/(otherParam)?/:pathParam2?"
    

    并对其进行测试:

    const re = pathToRegexp(path)
    
    console.log(re.exec("/to/page/1"))
    // ["/to/page/1", "1", undefined, undefined]
    
    console.log(re.exec("/to/page/1/otherParam/2"))
    // ["/to/page/1/otherParam/2", "1", "otherParam", "2"]
    

    【讨论】:

    • 哇,我的伪语法实际上非常接近;谢谢! react-router 及其不断变化、文档记录不完善的 API 上的一个问题 ;)
    猜你喜欢
    • 1970-01-01
    • 2010-09-25
    • 2021-10-24
    • 1970-01-01
    • 2011-01-07
    • 1970-01-01
    • 2023-01-22
    • 2016-07-04
    • 2014-06-02
    相关资源
    最近更新 更多