【问题标题】:React Router - how to constrain params in route matching?React Router - 如何在路由匹配中约束参数?
【发布时间】:2016-09-13 04:14:21
【问题描述】:

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

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

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

【问题讨论】:

    标签: reactjs react-router


    【解决方案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

    【讨论】:

    • 注意交换路由顺序会破坏逻辑,(\w+) 将匹配两个数字和字符串。更安全的正则表达式可能是 ([a-z]+) 因为这永远不会匹配数字。
    • 表达式缺失\&lt;Route exact path="/foo/:id(\\d+)" component={NumberRoute}/&gt;参考here
    • @Sean D. 你知道如何在 v3 中做到这一点吗?
    • 对我来说,只有删除多余的“\”才有效,所以path="/foo/:id(\d+)"
    【解决方案2】:

    目前我不确定 React 路由器是否可以做到这一点。但是,有一个简单的解决方案可以解决您的问题。只需在另一个组件中进行 int/alpha 检查,如下所示:

    <Router>
        <Route path="/:index" component={Child0} />
    </Router>
    
    const Child0 = (props) => {
        let n = props.params.index;
        if (!isNumeric(n)) {
            return <Child1 />;
        } else {
            return <Child2 />;
        }
    }
    

    * 请注意,上面的代码不会运行,它只是为了说明我的意思。

    【讨论】:

      猜你喜欢
      • 2017-10-03
      • 2016-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-11
      • 1970-01-01
      • 2016-05-12
      • 2014-04-25
      相关资源
      最近更新 更多