【问题标题】:Regex to use params in path正则表达式在路径中使用参数
【发布时间】:2021-10-19 09:17:24
【问题描述】:

如何创建一个可以同时处理零、一个、另一个或两个参数的路径(反应路由器 v5)。

例如:

/offers /offers/q-shoes /offers/London /offers/London/q-shoes

我正在尝试以这种方式实现它,不幸的是在这种情况下路径 /offers/London/offers 未被捕获

import React from 'react';
import pathToRegexp from 'path-to-regexp';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';

import { Home, Browse } from './Pages';

const re = pathToRegexp('/offers/:location?/q-:search?');

const App = () => (
  <Router>
    <Switch>
      <Route path={re}>
        <Browse />
      </Route>
     
      <Route path="/">
        <Home />
      </Route>
    </Switch>
  </Router>
);

export default App;

【问题讨论】:

    标签: javascript regex react-router


    【解决方案1】:

    根据documentation,您可以使用字符串或字符串数​​组作为路径。

    pathToRegexp 函数返回一个 RegEx 对象,因此您不能使用它。相反,您应该使用一个字符串数组,其顺序是从更具体到不太具体。

    import React from "react";
    import {
      BrowserRouter as Router,
      Route,
      Switch,
      Link,
      withRouter
    } from "react-router-dom";
    
    const Component = withRouter((props) => {
      return (
        <div>
          <div>{props.title}</div>
          <div>{JSON.stringify(props.match.params)}</div>
        </div>
      );
    });
    
    const Home = () => <Component title="Home" />;
    const Browse = () => <Component title="Browse" />;
    const NoMatch = () => <Component title="NoMatch" />;
    
    const pathArray = ["/offers/:location?/q-:search?", "/offers/:location?"];
    
    const App = () => (
      <Router>
        <div style={{ display: "flex", flexDirection: "column" }}>
          <Link to="/">/Home</Link>
          <Link to="/offers">/offers</Link>
          <Link to="/offers/q-shoes">/offers/q-shoes</Link>
          <Link to="/offers/London">/offers/London</Link>
          <Link to="/offers/London/q-shoes">/offers/London/q-shoes</Link>
        </div>
        <Switch>
          <Route path={pathArray}>
            <Browse />
          </Route>
    
          <Route path="/">
            <Home />
          </Route>
          <Route>
            <NoMatch />
          </Route>
        </Switch>
      </Router>
    );
    
    export default App;
    

    【讨论】:

      猜你喜欢
      • 2021-08-18
      • 1970-01-01
      • 2018-12-20
      • 1970-01-01
      • 2017-06-19
      • 2021-07-29
      • 1970-01-01
      • 2020-09-30
      • 2014-05-09
      相关资源
      最近更新 更多