Uncaught TypeError: (0 , _reactRouter.withRouter) 在 react-router 2.4.0 中以编程方式导航路由时不是一个函数

Posted

技术标签:

【中文标题】Uncaught TypeError: (0 , _reactRouter.withRouter) 在 react-router 2.4.0 中以编程方式导航路由时不是一个函数【英文标题】:Uncaught TypeError: (0 , _reactRouter.withRouter) is not a function when navigating to route programmatically in react-router 2.4.0 【发布时间】:2016-09-15 07:50:54 【问题描述】:

我正在使用react-router 2.4.0 并希望以编程方式链接到另一条路线(我在使用<Link> 之前所做的)。

这在SO post 中有很好的解释,他们在2.4.x 中说你应该使用带有withRouter 的装饰器模式,所以我使用以下代码:

import withRouter from 'react-router' // further imports omitted


class CreateJobItemFormRaw extends React.Component 
  ...


const CreateJobItemForm = withRouter(CreateJobItemFormRaw)
export default CreateJobItemForm

然后在其他文件中,我使用

import CreateJobItemForm from './CreateJobItemForm'

但是,通过这种方法,我的应用不再呈现,控制台输出:

CreateJobItemForm.js:76 Uncaught TypeError: (0 , _reactRouter.withRouter) is not a function

谁能帮我解决这个问题?

【问题讨论】:

【参考方案1】:

我相信您实际上使用的是 react-router 2.4.0,但在我的情况下,值得仔细检查我的 package.json 确实执行了该版本。我这样修改了我的 package.json:

"dependencies": 
  "react-router": "^2.4.0",
  ...

希望这会有所帮助。

【讨论】:

为我工作,谢谢! npm update 命令还不够,我不得不卸载 react-router 然后创建一个 npm install react-router@2.8.1 以使其更新。【参考方案2】:

在对另一个答案的评论中,您链接到了这个问题,并说您正在尝试使用 react-router 2.4+ 进行导航。尝试将 PropType 规范放入文件中,看看是否会给您任何警告。例如:

// PropTypes
Example.propTypes = 
  router: React.PropTypes.shape(
    push: React.PropTypes.func.isRequired
  ).isRequired
;

【讨论】:

感谢您的回答!我确实输入了propTypes,但问题仍然存在。奇怪的是我的整个应用程序根本没有,即使最初使用 withRouter 的组件甚至没有安装...... 提供给浏览器的包是否有可能过期。即错误的那个。我曾经看到过这样的事情,webpack 花了很长时间来重建 bundle.js 文件,我刷新了浏览器,它选择了一个旧的。你可以在里面放一个debugger; 语句,然后检查 react-router 放在this.props 上的内容,看看它对你来说是否合理...... 是的,伙计们,如果有人走到这一步,别忘了重新启动 webpack 或重新捆绑:P 它为我做的【参考方案3】:
import  withRouter  from 'react-router-dom'

react-router v4.x

【讨论】:

我在 v5 中有这个,但它仍然不能解决问题:TypeError: (0 , _reactRouterDom.withRouter) is not a function 因为它解决了我的 withRouter 问题。所以说谢谢。【参考方案4】:

在我的情况下,我升级到 react-router v6 并发现 withRouter 已被删除,应该改用钩子。

在此处升级文档: https://reactrouter.com/docs/en/v6/upgrading/v5#upgrade-to-react-router-v51

随着升级到 v5.1,您应该将 withRouter 的所有用法替换为钩子。

这里是钩子的详细指南: https://reacttraining.com/blog/react-router-v5-1/

【讨论】:

以上是关于Uncaught TypeError: (0 , _reactRouter.withRouter) 在 react-router 2.4.0 中以编程方式导航路由时不是一个函数的主要内容,如果未能解决你的问题,请参考以下文章

Uncaught TypeError: (0 , _reactRouter.withRouter) 在 react-router 2.4.0 中以编程方式导航路由时不是一个函数

Uncaught TypeError: _react2.default.createContext is not a function

reactjs Uncaught TypeError: Cannot read property 'location' of undefined

JQuery对象调用reset方法:Uncaught TypeError: $(...).reset is not a function

Uncaught TypeError: str.replace is not a function

Vue.js 在组件中使用本地 javascript 文件函数:Uncaught TypeError: __WEBPACK_IMPORTED_MODULE_0__.writeSomething is