我如何拥有可选的*非*参数URL部件?

时间:2018-01-17 21:16:38

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

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

TREX.name='TREX'
DHER.name='DHER'
df_list = [TREX,DHER]
idx, v = [], []
for i, df in enumerate(df_list, 1):
    idx.append(df.name)
    v.append(len(df.columns))
df = pd.DataFrame(v, index=idx, columns=['noOfColumn'])
df['pct'] = df['noOfColumn'] / DELF.inp.nunique()
df
Out[55]: 
      noOfColumn   pct
TREX           3  0.75
DHER           2  0.50

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

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

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

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

1 个答案:

答案 0 :(得分: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"]