問題
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, 3] },
{ id: 2, name: "Kim", friends: [0, 1, 3] },
{ id: 3, name: "David", friends: [1, 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 <li>
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/