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

如何获取React路由中的标识字段?以/category/1/等路由为例

获取路由中的标识字段(如category/catalog)

针对你给出的React Router v6路由配置,要从/category/1/或/catalog/1/这类路径里提取开头的标识字段,这里有两种实用方法:

方法一:路径字符串拆分提取

借助useLocation钩子拿到当前路径,拆分后取第一个有效分段即可:

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

function Categories() {
  const { pathname } = useLocation();
  // 拆分路径并过滤空字符串(路径开头的/会生成空元素)
  const pathParts = pathname.split('/').filter(part => part);
  // 第一个非空分段就是目标标识字段
  const identifier = pathParts[0]; // 对应'category'或'catalog'

  return (
    <div>当前路由标识: {identifier}</div>
  );
}

方法二:路由匹配规则提取

如果想更贴合路由配置逻辑,可以用useMatch匹配路由模式来提取:

方式1:合并路由配置(推荐)

先把两个路由合并成带动态参数的统一路由:

<Routes>
  <Route path='/:identifier/:id/' element={<Categories />} />
</Routes>

然后在组件里直接从匹配参数中获取:

import { useMatch } from 'react-router-dom';

function Categories() {
  const match = useMatch('/:identifier/:id/');
  const identifier = match?.params?.identifier;

  return (
    <div>当前路由标识: {identifier}</div>
  );
}

方式2:保留原有路由配置

如果不想修改现有路由,可同时匹配两个模式后判断:

import { useMatch } from 'react-router-dom';

function Categories() {
  const match = useMatch(['/category/:id/', '/catalog/:id/']);
  const identifier = match?.pathname.startsWith('/category') ? 'category' : 'catalog';

  return (
    <div>当前路由标识: {identifier}</div>
  );
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 05:54:17