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

2024-06-26

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

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

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


React-router v4 现在允许您使用正则表达式来匹配参数 --https://reacttraining.com/react-router/web/api/Route/path-string 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 https://github.com/pillarjs/path-to-regexp/tree/v1.7.0#custom-match-parameters

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

React Router - 如何约束路由匹配中的参数? 的相关文章