php做網(wǎng)站主要怎么布局百度明星人氣排行榜
目錄
- 1,作用
- 2,實(shí)現(xiàn)獲取 match 對象
- 2.1,match 對象的內(nèi)容
- 2.2,注意點(diǎn)
- 2.3,實(shí)現(xiàn)
1,作用
之前在介紹 2.3 match 對象 時,提到了 react-router 使用第3方庫 path-to-regexp 來匹配路徑正則。
我們也利用它(版本v6.2.2),來手動實(shí)現(xiàn)一個獲取類似 match
對象的方法。
2,實(shí)現(xiàn)獲取 match 對象
2.1,match 對象的內(nèi)容
- 不匹配時,返回
null
。 - 匹配時,返回一個對象
比如對下面的路由組件來說,
<Route path="/news/:id" component={News}></Route>
當(dāng)訪問 http://localhost:5173/news/123
時,返回的對象:
{"path": "/news/:id","url": "/news/123","isExact": true,"params": {"id": "123"}
}
2.2,注意點(diǎn)
先做個測試,看下返回內(nèi)容。
import { pathToRegexp } from "path-to-regexp";const path = "/news/:id";
const keys = [];
const regExp = pathToRegexp(path, keys);
console.log(regExp);
const result = regExp.exec(location.pathname);
console.log(result);
console.log(keys);
regExp
一個正則對象,
/^\/news(?:\/([^\/#\?]+?))[\/#\?]?$/i
result
匹配的結(jié)果,
["/news/123","123"
]
keys
的結(jié)果,
[{"name": "id","prefix": "/","suffix": "","pattern": "[^\\/#\\?]+?","modifier": ""}
]
除了 match.isExact
屬性,其他的東西都有了。而 match.isExact
可通過 location.pathname === result[0]
判斷。
另外,還需要注意一點(diǎn),<Route>
組件可以設(shè)置 exact
來表示是否精確匹配。比如,
<Route path="/news/:id" exact></Route>
此時訪問 http://localhost:5173/news/123/xxx
是并不匹配,match
為 null
。
而 path-to-regexp 的默認(rèn)配置項,是匹配到路徑字符串結(jié)尾。所以這個配置項就相當(dāng)于 exact
。
2.3,實(shí)現(xiàn)
import { pathToRegexp } from "path-to-regexp";/*** 返回一個類似 match 的對象。* @param {*} path 路徑規(guī)則* @param {*} pathname 真實(shí)的地址* @param {*} options react-router-dom 的 Route 組件的配置項。*/
export default function matchPath(path, pathname, options) {const keys = [];const regExp = pathToRegexp(path, keys, getOptions(options));const result = regExp.exec(pathname);if (!result) {return null;}const params = getParams(result.slice(1), keys);return {path,url: result[0],isExact: pathname === result[0],params,};
}/*** 返回符合 path-to-regexp 的配置項屬性。* @param {*} options* @returns*/
function getOptions(options = {}) {const defaultOptions = {exact: false, // 不精確匹配sensitive: false, // 大小寫敏感strict: false, // 嚴(yán)格模式};const opts = {...defaultOptions,...options,};return {end: opts.exact, // 更改 keysensitive: opts.sensitive,strict: opts.strict,};
}function getParams(result, keys) {const obj = {};keys.forEach((f, index) => {obj[f.name] = result[index];});return obj;
}
測試1,
const match = pathMatch("/news/:id/:no", location.pathname);
當(dāng)訪問 http://localhost:5173/news/123/asd
時返回,
{"path": "/news/:id/:no","url": "/news/123/asd","isExact": true,"params": {"id": "123","no": "asd"}
}
測試2,
const match = pathMatch("/news/:id/:no", location.pathname);
當(dāng)訪問 http://localhost:5173/news/123/asd/xxx
時返回,
{"path": "/news/:id/:no","url": "/news/123/asd","isExact": false,"params": {"id": "123","no": "asd"}
}
以上。