如何用JavaScript实现可选函数参数,结合React Router matchPath构建匹配函数
基于React Router matchPath的路径匹配函数优化需求
我需要用React Router的matchPath实现路径条件判断,目前写了一段基础代码,但需要调整以满足以下要求:
- 函数第一个参数仅接受
MyKey中的foo或bar取值 - 支持可选参数功能(可省略第一个参数,此时自动匹配
foo或bar的子路径) - 匹配规则:
http://localhost:3000/foo/sub→ 返回truehttp://localhost:3000/bar/sub→ 返回truehttp://localhost:3000/test/sub→ 返回falsehttp://localhost:3000/foo/sub/anothersub→ 返回true
原代码如下:
import { matchPath } from "react-router"; export const MyKey = { Foo: "foo", Bar: "bar", Home: "", } as const; export const subPageMatch = ( key: // 该参数可为`foo`或`bar`, path: string, ) => { return !!matchPath(path, { path: `/${key}/:subPage`, }); };
希望支持两种调用方式:
// 传入指定key const test1 = subPageMatch(MyKey.Foo, pathname); // 省略key,自动匹配foo或bar的子路径 const test2 = subPageMatch(pathname);
解决方案
以下是调整后的完整代码,满足所有需求:
import { matchPath } from "react-router"; export const MyKey = { Foo: "foo", Bar: "bar", Home: "", } as const; // 定义仅允许foo/bar的类型约束 type ValidKey = typeof MyKey.Foo | typeof MyKey.Bar; // 函数重载,明确两种调用方式的类型 export function subPageMatch(path: string): boolean; export function subPageMatch(key: ValidKey, path: string): boolean; export function subPageMatch(arg1: ValidKey | string, arg2?: string): boolean { // 处理参数逻辑:区分单参数/双参数场景 let targetKeys: ValidKey[]; let targetPath: string; if (arg2 === undefined) { // 仅传一个参数时,自动匹配foo和bar的子路径 targetKeys = [MyKey.Foo, MyKey.Bar]; targetPath = arg1 as string; } else { // 传两个参数时,匹配指定key的子路径 targetKeys = [arg1 as ValidKey]; targetPath = arg2; } // 遍历目标key,只要有一个匹配成功就返回true return targetKeys.some(key => { return !!matchPath(targetPath, { // 使用`:subPage*`允许参数包含斜杠,适配多层子路径 path: `/${key}/:subPage*`, // 关闭精确匹配,确保长路径也能被匹配 exact: false, }); }); }
关键说明
- 参数类型约束:通过
ValidKey类型限定第一个参数只能是MyKey.Foo或MyKey.Bar,避免传入无效值 - 可选参数支持:利用函数重载实现两种调用方式,兼顾指定key匹配和自动匹配场景
- 匹配规则优化:
- 路径模板改为
/${key}/:subPage*,其中*表示参数可包含斜杠,确保/foo/sub/anothersub这类多层子路径能被匹配 - 显式设置
exact: false,避免因路径长度问题导致匹配失败
- 路径模板改为
- 多key匹配逻辑:省略第一个参数时,用
some方法遍历foo和bar,只要有一个匹配成功就返回true
测试验证
const path1 = "/foo/sub"; const path2 = "/bar/sub"; const path3 = "/test/sub"; const path4 = "/foo/sub/anothersub"; console.log(subPageMatch(MyKey.Foo, path1)); // true console.log(subPageMatch(MyKey.Bar, path2)); // true console.log(subPageMatch(MyKey.Foo, path3)); // false console.log(subPageMatch(path4)); // true console.log(subPageMatch(path3)); // false
内容的提问来源于stack exchange,提问作者meez
相关产品推荐
相关产品推荐

