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

React Router正则匹配:如何在路径中间替换列表ID

替换路径中的列表ID并导航到新路径

要实现点击按钮后修改当前路径里的列表ID,同时保留/items及后续子路径,可以用正则表达式精准匹配并替换路径中的ID部分,具体实现如下:

完整代码实现

import { useNavigate, useLocation } from 'react-router-dom';

// 组件内代码
const navigate = useNavigate();
const location = useLocation();

const handleListChange = (listId: number) => {
  // 正则匹配 /list/[数字]/ 结构,仅替换列表ID部分
  const updatedPath = location.pathname.replace(/\/list\/\d+\//, `/list/${listId}/`);
  // 导航到修改后的路径,同时保留原查询参数
  navigate({
    pathname: updatedPath,
    search: location.search
  });
};

关键逻辑说明

  • 正则表达式:/\/list\/\d+\// 精准匹配路径中类似 /list/3/ 的片段:
    • \/list\/ 匹配固定的 /list/ 字符串
    • \d+ 匹配一个或多个数字(即原有列表ID)
    • 末尾的 \/ 确保匹配到ID后的斜杠,避免误匹配其他带数字的路径
  • 路径替换:用新的listId替换匹配片段,保证/items及后续子路径完全保留
  • 保留查询参数:如果原路径带有?xxx=yyy这类查询参数,通过location.search可直接保留,无需额外处理

示例验证

假设当前路径为 https://localhost:3000/list/3/items/detail?sort=asc,点击按钮传入listId=5后,新路径会变为 https://localhost:3000/list/5/items/detail?sort=asc,完全符合需求。

内容的提问来源于stack exchange,提问作者Adrian

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 06:25:21