React Router 4 Regex路径 - 匹配不查找参数

时间:2018-02-10 17:08:55

标签: reactjs react-router react-router-v4

我试图让反应路由器4进行正则表达式模式匹配,但不幸的是 this.props.match.params.id没有正确解析路径,并显示为未定义。

我希望能够访问的路径示例:

  1. / GPS
  2. / GPS /空气
  3. / GPS / a0b6dc45-11a1-42c5-非银-a62822d109dc
  4. / GPS /空气/ a0b6dc45-11a1-42c5-非银-a62822d109dc
  5. 我的组件:

    import React from "react";
    import PropTypes from "prop-types";
    import { withRouter, } from "react-router";
    import { Switch, Route } from "react-router-dom";
    
    class Foo extends React.Component {
        render(){
            console.log(this.props.match);
            return <div>Match: {this.props.match.params.id}</div>
        }
    } 
    
    const industryRegex = "(air|motor|ship)";
    const guidRegex = "([0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})?"; // Note the questionmark ? at the end
    
    const pathId =            `/gps/:id${guidRegex}`;
    const pathIndustry =      `/gps/:industryType${industryRegex}`;
    const pathIndustryAndId = `/gps/:industryType${industryRegex}/:id${guidRegex}`;
    
    console.log(pathId);
    console.log(pathIndustry);
    console.log(pathIndustryAndId);
    
    const AppComponent = ({...props}) => {
        return (
            <Switch>
                <Route path={pathId}                     component={Foo} />
                <Route path={pathIndustry}               component={Foo} />
                <Route path={pathIndustryAndId}          component={Foo} />
            </Switch>
        )
    };
    
    export default withRouter(AppComponent);
    

    尝试以下路径/gps/a0b6dc45-11a1-42c5-afdb-a62822d109dc会导致this.props.match.params.id未定义。

    任何帮助非常感谢

1 个答案:

答案 0 :(得分:1)

您在行业正则表达式末尾错过了一个问号,并将其标记为通过案例3的选项。否则,您的正则表达式适用于您所述的所有案例。

固定正则表达式应如下所示:/gps/:industryType(air|motor|ship)?/:id([0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})?

专业提示:对于路由器4,您可以在此处测试正则表达式并验证所有用例:https://pshrmn.github.io/route-tester/