React Router - 如何限制路由匹配中的参数? [英] React Router - how to constrain params in route matching?

查看:67
本文介绍了React Router - 如何限制路由匹配中的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I don't really get how to constrain params with, for example a regex.
How to differentiate these two routes?

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

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

And prevent "/123" from firing the first route?

推荐答案

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

React-router v4 now allows you to use regexes to match params -- 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

这篇关于React Router - 如何限制路由匹配中的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆