1. 基础依赖path-to-regexp
react-router提供了专门的路由匹配方法matchPath(位于packages/react-router/modules/matchPath.js),该方法背后依赖的其实是path-to-regexp包。
path-to-regexp输入是路径字符串(也就是Route中定义的path的值),输出包含两部分
● 正则表达式(re)
● 一个数组(keys)(用于记录param的key信息)
2. matchPath核心
matchPath方法首先通过path-to-regexp的方法来获取Route上定义的path对应的正则,再将生成的正则表达式与url中的pathname做正则匹配判断是否匹配。
把地址中的路径和属性中的path进行匹配,返回匹配结果
let pathToRegExp = require('path-to-regexp');
function compilePath(path, options) {const keys = [];const regexp = pathToRegExp(path, keys, options);return { keys, regexp };
}
/*** 把地址中的路径和属性中的path进行匹配,返回匹配结果 * @param {*} pathname 地址中的路径* @param {*} options 属性对象*/
function matchPath(pathname, options = {}) {// exact 是否精确匹配 sensitive 是否大小写敏感let { path = "/", exact = false, strict = false, sensitive = false } = options;let { keys, regexp } = compilePath(path, { end: exact, strict, sensitive });let match = regexp.exec(pathname);if (!match) return null;const [url, ...groups] = match;//pathname=/user/list regxp =/\/user/ url=/userconst isExact = pathname === url;//是否完整匹配url路径return {path,//Route 里的路径url,//正则匹配到的浏览器路径的部分isExact,// 是否精确匹配params: keys.reduce((memo, key, index) => {//路径参数对象memo[key.name] = groups[index];return memo;}, {})}}
export default matchPath;