You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript实现可选函数参数,结合React Router matchPath构建匹配函数

基于React Router matchPath的路径匹配函数优化需求

我需要用React Router的matchPath实现路径条件判断,目前写了一段基础代码,但需要调整以满足以下要求:

  1. 函数第一个参数仅接受MyKey中的foo或bar取值
  2. 支持可选参数功能(可省略第一个参数,此时自动匹配foo或bar的子路径)
  3. 匹配规则:
    • http://localhost:3000/foo/sub → 返回true
    • http://localhost:3000/bar/sub → 返回true
    • http://localhost:3000/test/sub → 返回false
    • http://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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 18:08:12