首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Router 4 Regex路径-匹配没有找到参数

Router 4 Regex路径-匹配没有找到参数
EN

Stack Overflow用户
提问于 2018-02-10 17:08:54
回答 1查看 33.6K关注 0票数 13

我正在尝试使regex模式匹配用于反应性路由器4,但不幸的是,this.props.match.params.id 没有正确地解析路径,而是显示为未定义的.

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

  1. /gps
  2. /全球定位系统/空气
  3. /gps/a0b6dc45-11a1-42c5-非行-a62822d109dc
  4. /gps/air/a0b6dc45-11a1-42c5-非行-a62822d109dc

我的组成部分:

代码语言:javascript
运行
复制
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未定义。

任何帮助都很感激

EN

回答 1

Stack Overflow用户

发布于 2018-02-10 19:02:06

在行业regex结束时,您遗漏了一个问号,将其标记为传递案例3的选项。否则,regex将适用于所有声明的案例。

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

提示:对于react路由器4,您可以在这里测试regex并验证所有用例:https://pshrmn.github.io/route-tester/

票数 17
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48723370

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档