小编典典

React Router-如何在路由匹配中约束参数?

reactjs

我真的不知道如何用正则表达式来约束参数。
如何区分这两种路线?

  <Router>
    <Route path="/:alpha_index" component={Child1} />
    <Route path="/:numeric_index" component={Child2} />
  </Router>

并阻止“ / 123”触发第一条路线?


阅读 364

收藏
2020-07-22

共1个答案

小编典典

React-router v4现在允许您使用正则表达式来匹配参数-https: //reacttraining.com/react-
router/web/api/Route/path-string

const NumberRoute = () => <div>Number Route</div>;
const StringRoute = () => <div>String Route</div>;

<Router>
    <Switch>
        <Route exact path="/foo/:id(\\d+)" component={NumberRoute}/>
        <Route exact path="/foo/:path(\\w+)" component={StringRoute}/>
    </Switch>
</Router>

更多信息:https : //github.com/pillarjs/path-to-regexp/tree/v1.7.0#custom-
match-parameters

2020-07-22