ReactJs this.props.router 未定义 [英] ReactJs this.props.router undefined
问题描述
您好,我正在学习 React js,但遇到了一个问题.当我尝试使用 react router 改回主页时,出现以下错误:
<块引用>未捕获的类型错误:无法读取未定义的属性 'push'
这是我的代码,如您所见,我正在调用导航功能:
我的带有路由器的 client.js:
如果我将 this.props.router.push('/');
替换为 this.props.history.push('/');
它工作正常.可能是什么问题?
您缺少一个调用 super()
的构造函数方法.super()
调用父类的构造函数,需要将父类的属性正确传递给该组件.您需要它来访问传递给组件的任何属性,包括 router
.
布局类的顶部应如下所示.
export default class Layout extends React.Component {构造函数(道具){超级(道具)}导航(){...}使成为() {...}}
编辑 1:反应路由器
通过this.props.router
进行导航时,您还需要使用新的withRouter
.您可以通过将您的组件作为参数传递并导出它来完成此操作.withRouter
函数只是将您的组件包装在另一个组件中,该组件将路由器 prop 向下传递给您的组件.我应该指出,还有其他方式进行程序化路由(单例、上下文等),但是在使用 this.props.router.push
时,您需要使用 withRouter代码>.
import { withRouter } from 'react-router'类布局扩展 React.Component {构造函数(道具){超级(道具)}导航(){...}使成为() {...}}导出默认 withRouter(Layout)
Hello I am learning React js and I have came across a problem. When I try to change back to the main page using react router i get the following error:
Uncaught TypeError: Cannot read property 'push' of undefined
Here is my code, as you can see I am calling the navigate function:
My client.js with router:
If I replace this.props.router.push('/');
with this.props.history.push('/');
it works fine.
What could be the problem?
You are missing a constructor method with a call to super()
. super()
calls the constructor of the parent class and is needed to properly pass the properties of the parents class to this component. You would need this to access any properties passed to the component, including router
.
The top of your layout class should look like this.
export default class Layout extends React.Component {
constructor(props) {
super(props)
}
navigate() {
...
}
render() {
...
}
}
Here are the docs on how classes work in ES6!
Edit 1: React Router
You also need to use the new withRouter
when doing navigation via this.props.router
. You do this by passing your component as an argument and exporting that. The withRouter
function just wraps your component in another component that passes the router prop down to your component. I should point out that there are other ways of doing programmatic routing (singletons, context, etc.), but when using this.props.router.push
you will need to use withRouter
.
import { withRouter } from 'react-router'
class Layout extends React.Component {
constructor(props) {
super(props)
}
navigate() {
...
}
render() {
...
}
}
export default withRouter(Layout)
这篇关于ReactJs this.props.router 未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!