React Router - 如何限制路由匹配中的参数?

IT技术 reactjs react-router
2021-05-06 08:51:23

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

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

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

2个回答

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

我不确定目前是否可以使用 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 />;
    }
}

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