区别React-Router中match的path和url

前端之家收集整理的这篇文章主要介绍了区别React-Router中match的path和url前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

问题

React Router开发中有关<Route>组件的match属性的两个属性path和url,容易让人混淆,特别记录于此。

解释

官方描述如下:

  • path - (string) The path pattern used to match. Useful for building nested <Route>s
  • url - (string) The matched portion of the URL. Useful for building nested <Link>s
  • @H_404_13@

    path用来标识路由匹配的URL部分。React Router使用了Path-to-RegExp库将路径字符串转为正则表达式。然后正则表达式会匹配当前路径。

    当路由路径和当前路径成功匹配,会生成一个对象match。match对象有更多关于URL和path的信息。这些信息可以通过它的属性获取,如下所示:

    • match.url.返回URL中匹配部分的字符串。用于创建嵌套的<Link>很有用。
    • match.path.用于匹配路径模式。用来创建嵌套的<Route>。
    • match.isExact.返回布尔值,如果准确(没有任何多余字符)匹配则返回true。
    • match.params.返回一个对象包含Path-to-RegExp包从URL解析的键值对。
    • @H_404_13@

      只有完全理解了<Route>的这个match对象属性及其有关属性,才能算是掌握了基本类型嵌套路由开发的基础部分(本人拙见,仅供参考)。

      举例1

      我们不妨考虑一个小例子,如下所示:

      观察路由"/users/:userId"
      此例中,match.path的返回值将是 "/users/:userId"。
      而match.url 的返回值将是:userId的值,例如"users/5"。
      请注意上面官方描述中,match.path指用于匹配的模式部分,代表了一种格式,而match.url代表一个具体的计算后的路径表达值。

      举例2

      根据上面的解释,match.path和match.url的值是相同的,此时你想使用哪一个都行。但是,本人建议还是遵循官方解释,在嵌套式<Link>组件中尽量使用match.url,而在嵌套式<Route>组件中尽量使用match.path。
      从官方网站也会观察到上面混合使用情况。

      在Recursive Paths部分,你会观察到如下代码

      import React from "react";
      import { BrowserRouter as Router,Route,Link } from "react-router-dom";
      
      const PEEPS = [
        { id: 0,name: "Michelle",friends: [1,2,3] },{ id: 1,name: "Sean",friends: [0,{ id: 2,name: "Kim",1,{ id: 3,name: "David",2] }
      ];
      
      const find = id => PEEPS.find(p => p.id == id);
      
      const RecursiveExample = () => (
        <Router>
          <Person match={{ params: { id: 0 },url: "" }} />
        </Router>
      );
      
      const Person = ({ match }) => {
        const person = find(match.params.id);
      
        return (
          <div>
            <h3>{person.name}’s Friends</h3>
            <ul>
              {person.friends.map(id => (
                <li key={id}>
                  <Link to={`${match.url}/${id}`}>{find(id).name}</Link>
                </li>
              ))}
            </ul>
            <Route path={`${match.url}/:id`} component={Person} />
          </div>
        );
      };
      
      export default RecursiveExample;

      而在佳文https://www.sitepoint.com/react-router-v4-complete-guide/
      中也使用了混合使用的情况(见“Demo 3: Nested routing with Path parameters”一节):

      const Products = ({ match }) => {

      const productsData = [
      {
      id: 1,
      name: 'NIKE Liteforce Blue Sneakers',
      description: 'Lorem ipsum dolor sit amet,consectetur adipiscing elit. Proin molestie.',
      status: 'Available'

      },//Rest of the data has been left out for code brevity

      ];
      /* Create an array of &lt;li&gt; items for each product
      var linkList = productsData.map( (product) => {
      return(
      <li>
      <Link to={${match.url}/${product.id}}>
      {product.name}
      </Link>
      </li>
      )

      })

      return(
      <div>
      <div>
      <div>
      <h3> Products</h3>
      <ul> {linkList} </ul>
      </div>
      </div>

      <Route path={`${match.url}/:productId`}
              render={ (props) => <Product data= {productsData} {...props} />}/>
          <Route exact path={match.url}
              render={() => (
              <div>Please select a product.</div>
              )}
          />
      </div>

      )
      }

      引用

      1.https://www.zcfy.cc/article/react-router-v4-the-complete-guide-mdash-sitepoint-4448.html
      2.https://teamtreehouse.com/community/what-is-the-difference-between-path-and-url-in-match-prop-of-reactrouter-route-component-react-router-basics
      3.https://reacttraining.com/react-router/

猜你在找的React相关文章