React路由点击链接URL变更但始终渲染同一页面问题排查
React-router-dom路由始终渲染同一页面问题解决方案
核心问题原因
你的代码中存在Route组件属性拼写错误,React组件属性大小写敏感,错误拼写的路径属性不会被路由识别:
- 两处将路径属性
path错写为patch - 两处将路径属性
path错写为大写开头的Path
没有正确配置path属性的Route会匹配所有路径,结合Switch组件“匹配到第一个符合规则的路由就停止匹配”的逻辑,所有除/、/agents之外的路径都会命中拼写错误的RmSkills路由,也就是你看到的“Job Category”页面。
修复步骤
- 修正所有路由的路径属性拼写,统一改为小写
path:
修改以下错误代码行:
// 修正前 <Route patch="/rmskills" component={RmSkills} exact /> <Route patch="/rmtable" component={Rmtable} exact /> <Route Path="/custom" component={Custom} /> <Route Path="/contactmodel" component={Contactmodel} /> // 修正后 <Route path="/rmskills" component={RmSkills} exact /> <Route path="/rmtable" component={Rmtable} exact /> <Route path="/custom" component={Custom} /> <Route path="/contactmodel" component={Contactmodel} />
- 版本适配校验:你当前使用的是react-router-dom v5的语法(
Switch、component属性),如果你的项目安装的是v6版本,需要降级到兼容的v5版本:
# npm 安装 npm install react-router-dom@5.3.4 # yarn 安装 yarn add react-router-dom@5.3.4
- 可选优化:在
Switch最后添加兜底404路由,避免路径匹配失败时出现空白:
<Route path="*" component={NotFoundPage} />
- 校验导航组件:确认页面跳转使用的是react-router-dom提供的
Link组件,而非原生a标签,避免页面全量刷新。
内容的提问来源于stack exchange,提问作者Usman Mughal
相关产品推荐
相关产品推荐

