加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

区别React-Router中match的path和url

发布时间:2020-12-15 06:26:14 所属栏目:百科 来源:网络整理
导读:问题 React Router开发中有关Route组件的match属性的两个属性path和url,容易让人混淆,特别记录于此。 解释 官方描述如下: path - (string) The path pattern used to match. Useful for building nested Routes url - (string) The matched portion of th

问题

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

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解析的键值对。

只有完全理解了<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/

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读