reactjs - 未捕获的类型错误 : Cannot read property 'history' of undefined

标签 reactjs react-router

我正在使用react-router v4.1.1,当我尝试使用链接组件时 - 我收到警告:

Failed context type: The context `router` is marked as required in `Link`, 
but its value is `undefined`.

还有一个错误:

Uncaught TypeError: Cannot read property 'history' of undefined

此字符串的链接组件中存在错误:

var href = this.context.router.history.createHref(typeof to === 'string' ? { pathname: to } : to);

为什么路由器未定义?

我正在我的一个组件中导入 BrowserRouter 和 Route,该组件仅负责渲染菜单中选定的页面。还有一个 Link 导入到另一个组件中,该组件实际上是一个带有无序列表的 Menu 组件。

如果需要,我将附上所有组件。 感谢您的帮助。

最佳答案

如果你想使用这个

var href = this.context.router.history.createHref(typeof to === 'string' ? { pathname: to } : to);

您需要向您的组件注册路由器,如下所示 在您的组件中放入此代码

 static contextTypes = { 
   router: React.PropTypes.object 
} 

关于reactjs - 未捕获的类型错误 : Cannot read property 'history' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44515263/

相关文章:

javascript - React Native Button onPress 不起作用

reactjs - mapStateToProps 函数,定位帖子的 id 而不是所有帖子

javascript - React如何更新n层以上父组件的状态

javascript - React 中动态生成的按钮不会重新渲染

reactjs - 链接内的 React-router 可点击元素

reactjs - React Router 不响应 Param

javascript - 使用 MongoDB 的 Visual Studio Code 中的验证错误

reactjs - 如何解决在尝试 npm i React 项目中的模块时出现的错误

reactjs - 使用 create-react-app 部署 github 页面时出现 React-router 问题

reactjs - 如何渲染NotFound组件react-router-config