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

React Router运行报错TypeError: Object(...) is not a function问题求助

React Router 报错 TypeError: Object(...) is not a function 解决方案

核心原因

报错90%以上是 react-router-dom 版本不兼容导致的:目前npm默认安装的是v6版本,而你写的路由代码是v5的API规范,两者不兼容。另外你贴出的代码还缺失了根组件的定义部分。

解决方案

方案1:适配v6版本(推荐使用最新版)

v6对路由API做了大量破坏性更新,你需要按以下规则修改代码:

  • 从 react-router-dom 额外引入 Routes 组件,所有 Route 必须嵌套在 Routes 内部
  • 替换原 component 属性为 element,属性值传入组件实例(要加尖括号)
  • 补全根组件的定义,优先用函数组件写法更简洁

修改后的完整代码示例:

import React from "react";
import "./index.css";
// 额外引入Routes
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import TwittersView from '../TwittersView/TwittersView';
import ArticlesView from '../ArticlesView/ArticlesView';
import NotesView from '../NotesView/NotesView';

// 补全根组件定义(函数组件写法)
export default function Root() {
  return (
    <BrowserRouter>
      <>
        <h1>hello world</h1>
        {/* 所有Route包裹在Routes内 */}
        <Routes>
          {/* component改为element,传组件实例 */}
          <Route exact path="/" element={<TwittersView />} />
          <Route path="/articles" element={<ArticlesView />} />
          <Route path="/notes" element={<NotesView />} />
        </Routes>
      </>
    </BrowserRouter>
  );
}

方案2:降级到v5版本

如果你学习的课程是基于v5讲解的,不想改代码可以直接降级到v5的最终稳定版,执行安装命令即可:
npm install react-router-dom@5.3.4
如果用yarn则执行:
yarn add react-router-dom@5.3.4
降级后原来的v5写法代码可以正常运行,注意要补全你缺失的根组件定义部分,示例如下:

// v5版本完整代码参考
import React from "react";
import "./index.css";
import { BrowserRouter, Route } from 'react-router-dom';
import TwittersView from '../TwittersView/TwittersView';
import ArticlesView from '../ArticlesView/ArticlesView';
import NotesView from '../NotesView/NotesView';

// 类组件写法补全定义
class Root extends React.Component {
  render() {
    return (
      <BrowserRouter>
        <>
          <h1>hello world</h1>
          <Route exact path="/" component={TwittersView} />
          <Route path="/articles" component={ArticlesView} />
          <Route path="/notes" component={NotesView} />
        </>
      </BrowserRouter>
    );
  }
}

export default Root;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 01:06:06