我怎样才能拥有可选的 *Non*-Parameter URL 部分?
How Can I Have Optional *Non*-Parameter URL Parts?
解释了如何定义包含多个可选参数的 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 版本中当然是可行的,但我看不到在当前版本中如何做到这一点。有没有办法指定可选的 parameter/non-parameter 配对,甚至只是可选的非参数?类似于:
<Route path="/to/page/:pathParam1?/(otherParam/:pathParam2?)" component={MyPage} />
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"]
<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 版本中当然是可行的,但我看不到在当前版本中如何做到这一点。有没有办法指定可选的 parameter/non-parameter 配对,甚至只是可选的非参数?类似于:
<Route path="/to/page/:pathParam1?/(otherParam/:pathParam2?)" component={MyPage} />
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"]