本文介绍了反应路由器 4 正则表达式路径 - 匹配找不到参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为 react router 4 进行正则表达式模式匹配,但不幸的是 this.props.match.params.id 没有正确解析路径,并显示为未定义.

I'm trying to have regex pattern matching for react router 4, but unfortunately the this.props.match.params.id is not parsing the path correctly, and shows up as undefined.

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

Examples of paths i want to be able to access:

  1. /gps
  2. /gps/air
  3. /gps/a0b6dc45-11a1-42c5-afdb-a62822d109dc
  4. /gps/air/a0b6dc45-11a1-42c5-afdb-a62822d109dc

我的组件:

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 未定义.

Trying the following path /gps/a0b6dc45-11a1-42c5-afdb-a62822d109dc results in this.props.match.params.id being undefined.

非常感谢任何帮助

推荐答案

您在行业正则表达式末尾缺少一个问号,以将其标记为通过案例 3 的选项.否则,您的正则表达式适用于您声明的所有内容案例.

You're missing a question mark at the end of the industry regex to mark it as option to pass your case 3. Otherwise you regex works for all your stated cases.

固定的正则表达式应如下所示:/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})?

The fixed regex should look like this: /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/

Pro tip: For react router 4, you can test your regex and validate all your use cases here: https://pshrmn.github.io/route-tester/

这篇关于反应路由器 4 正则表达式路径 - 匹配找不到参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 03:24