您好,登錄后才能下訂單哦!
React Router開發(fā)中有關(guān)<Route>組件的match屬性的兩個屬性path和url,容易讓人混淆,特別記錄于此。
官方描述如下:
path用來標(biāo)識路由匹配的URL部分。React Router使用了Path-to-RegExp庫將路徑字符串轉(zhuǎn)為正則表達式。然后正則表達式會匹配當(dāng)前路徑。
當(dāng)路由路徑和當(dāng)前路徑成功匹配,會生成一個對象match。match對象有更多關(guān)于URL和path的信息。這些信息可以通過它的屬性獲取,如下所示:
只有完全理解了<Route>的這個match對象屬性及其有關(guān)屬性,才能算是掌握了基本類型嵌套路由開發(fā)的基礎(chǔ)部分(本人拙見,僅供參考)。
我們不妨考慮一個小例子,如下所示:
觀察路由"/users/:userId"
此例中,match.path的返回值將是 "/users/:userId"。
而match.url 的返回值將是:userId的值,例如"users/5"。
請注意上面官方描述中,match.path指用于匹配的模式部分,代表了一種格式,而match.url代表一個具體的計算后的路徑表達值。
根據(jù)上面的解釋,match.path和match.url的值是相同的,此時你想使用哪一個都行。但是,本人建議還是遵循官方解釋,在嵌套式<Link>組件中盡量使用match.url,而在嵌套式<Route>組件中盡量使用match.path。
從官方網(wǎng)站也會觀察到上面混合使用情況。
在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>
<h4>{person.name}’s Friends</h4>
<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”一節(jié)):
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>
<h4> Products</h4>
<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/
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。