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=/user
    const 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;

3.route 渲染

在这里插入图片描述

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐