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

react-router-dom v5升级v6遇组件错误及路径读取问题求助

React Router v5 升级到 v6 报错解决方案

这两个错误都是React Router v6的API变更直接导致的,和其他版本兼容无关,具体原因和修复方式如下:

1. "[undefined] is not a component. All component children of must be a or <React.Fragment>" 错误

原因

React Router v6 中 <Routes> 组件的子元素只能是 <Route> 或 <React.Fragment>,不允许出现其他组件、文本或 undefined。常见触发场景:

  • 用条件渲染路由时直接写 {condition && <Route ... />},当 condition 为 false 时会返回 undefined
  • 在 <Routes> 下直接放置非 <Route> 组件(比如v5中<Switch>允许的写法)

修复方式

  • 条件渲染路由时,改用 <Route> 的 element 属性做判断,返回组件或 null:
    // 错误写法
    <Routes>
      {isLoggedIn && <Route path="/dashboard" element={<Dashboard />} />}
      <Route path="/login" element={<Login />} />
    </Routes>
    
    // 正确写法
    <Routes>
      <Route path="/dashboard" element={isLoggedIn ? <Dashboard /> : null} />
      <Route path="/login" element={<Login />} />
    </Routes>
    
  • 如果需要批量渲染路由,用 <React.Fragment> 包裹多个 <Route>:
    <Routes>
      <React.Fragment>
        <Route path="/resume/create" element={<ResumeCreate />} />
        <Route path="/resume/edit" element={<ResumeEdit />} />
      </React.Fragment>
      <Route path="/home" element={<Home />} />
    </Routes>
    

2. "Uncaught TypeError: Cannot read properties of undefined (reading 'pathname')" 错误

原因

React Router v6 移除了路由组件自动接收的 match、location、history 三个props,如果你还是用旧方式获取 location.pathname,就会因为 location 是 undefined 报错。

修复方式

函数组件(推荐)

使用 react-router-dom 提供的 useLocation 钩子获取路由信息:

// 错误写法(v5)
import React from 'react';

function ResumeCreate(props) {
  const { pathname } = props.location;
  // ...
}

// 正确写法(v6)
import React from 'react';
import { useLocation } from 'react-router-dom';

function ResumeCreate() {
  const location = useLocation();
  const { pathname } = location;
  // ...
}

类组件

v6 官方移除了 withRouter 高阶组件,你可以自己实现一个来传递路由信息:

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

// 自定义withRouter高阶组件
function withRouter(Component) {
  function ComponentWithRouterProp(props) {
    const location = useLocation();
    const navigate = useNavigate();
    const params = useParams();
    return <Component {...props} router={{ location, navigate, params }} />;
  }
  return ComponentWithRouterProp;
}

// 在类组件中使用
class ResumeCreate extends React.Component {
  render() {
    const { pathname } = this.props.router.location;
    // ...
  }
}

export default withRouter(ResumeCreate);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 03:33:20