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

React.js中如何使用Route匹配固定前缀的随机生成URL路径

问题原因

你的路由配置不符合React Router的匹配规则,核心问题两点:

  1. 未添加通配符或动态参数声明,如果使用的是React Router v6版本,默认不会匹配前缀相同但后续有内容的路径
  2. 没有做参数提取配置,无法在学生信息页拿到对应学生的标识

修复方案

方案1:标准动态路由写法(推荐)

路径结构更规范,参数提取更简单,是React官方推荐的传参方式

第一步:修改App.js路由配置

若使用React Router v5

return (
    <div>
      <Switch>
        <Route path="/" exact>
          <MainPage />
        </Route>
        <Route path="/register_student">
          <RegisterPage />
        </Route>
        <!-- 用:stuId声明动态参数 -->
        <Route path="/student_info/:stuId">
          <StudentInfo />
        </Route>
      </Switch>
    </div>
  );

若使用React Router v6(v6已废弃Switch组件,替换为Routes,渲染属性改为element)

import { Routes, Route } from 'react-router-dom';

return (
    <div>
      <Routes>
        <Route path="/" element={<MainPage />} />
        <Route path="/register_student" element={<RegisterPage />} />
        <Route path="/student_info/:stuId" element={<StudentInfo />} />
      </Routes>
    </div>
  );

第二步:修改Link跳转路径

将原来的/student_info_+学生标识的拼接规则,改为/student_info/+学生标识:

<Link to={`/student_info/${对应学生标识}`}>{学生姓名}</Link>

第三步:StudentInfo页面获取参数

v5和v6版本都可以用useParams钩子直接拿动态参数:

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

function StudentInfo() {
  const { stuId } = useParams();
  return (
        <div className="btn-textfield">
            {stuId}
        </div>
    );
}

方案2:保留原有路径拼接规则

如果不想修改现有跳转逻辑,直接给路由加通配符匹配所有前缀为/student_info_的路径

路由配置修改

v5版本

<Route path="/student_info_*">
  <StudentInfo />
</Route>

v6版本

<Route path="/student_info_*" element={<StudentInfo />} />

学生标识提取

在StudentInfo页面用useLocation拿到完整路径后截取标识即可:

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

function StudentInfo() {
  const { pathname } = useLocation();
  const stuId = pathname.replace('/student_info_','');
  return (
        <div className="btn-textfield">
            {stuId}
        </div>
    );
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 07:57:03