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

React应用中location.pathName始终为undefined导致页面无法跳转

问题分析与解决方案

核心问题

  1. 依赖版本不兼容:你同时安装了react-router@6.8.1和react-router-dom@5.2.0,跨大版本的路由包会导致功能异常,withRouter无法正常传递location属性。
  2. React Router 6已移除withRouter:从v6版本开始,官方不再提供withRouter高阶组件,原有方式无法获取路由信息。
  3. 属性名拼写错误:location对象里的路径属性是小写的pathname,你代码里写的pathName会直接返回undefined。

解决步骤

1. 统一路由依赖版本

先卸载旧版react-router-dom,安装与react-router同版本的包:

npm uninstall react-router-dom
npm install react-router-dom@6.8.1

用yarn的话:

yarn remove react-router-dom
yarn add react-router-dom@6.8.1

2. 修改组件获取路由信息的方式

React Router 6中,函数组件直接用useLocation钩子获取location,不需要withRouter:

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

const Header = () => {
  const location = useLocation();
  const pathName = location.pathname; // 修正属性名拼写

  return (
    // 你的HTML内容
  );
};

export default Header;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 08:59:14