无法读取反应中未定义的属性“推送" [英] Cannot read property 'push' of undefined in react
问题描述
导入 React, {PropTypes} from 'react';导出默认类登录扩展 React.Component {构造函数(道具){超级(道具)this.handleLogin = this.handleLogin.bind(this)}句柄登录(事件){event.preventDefault()//在这里做一些登录逻辑,如果成功:this.props.history.push(`/Home`)}使成为() {返回 (<div><form onSubmit={this.handleLogin}><input type='submit' value='登录'/></表单>
)}}
我在控制台中无法读取未定义的属性推送".现在如何在 react-router v4 中访问推送.
提前致谢!
默认情况下,在 react router 4 中不能使用 browserHistory,因为你可以在 react router 3 中使用,但你仍然可以使用不同的方式通过 withRouter 或 context 进行推送但我会推荐与路由器 HOC 一起使用.您应该使用 withRouter 高阶组件,并将其包装到将推送到历史记录的组件中.例如:
从react"导入React;import { withRouter } from "react-router-dom";class MyComponent 扩展了 React.Component {...我的功能(){this.props.history.push("/HOME");}...}导出默认 withRouter(MyComponent);
import React, {PropTypes} from 'react';
export default class Login extends React.Component {
constructor(props) {
super(props)
this.handleLogin = this.handleLogin.bind(this)
}
handleLogin(event) {
event.preventDefault()
// do some login logic here, and if successful:
this.props.history.push(`/Home`)
}
render() {
return (
<div>
<form onSubmit={this.handleLogin}>
<input type='submit' value='Login' />
</form>
</div>
)
}
}
I am getting Cannot read property 'push' of undefined in the console. Now how to access the push in the react-router v4.
thanks in advance!
By default use can't use browserHistory in react router 4 as you can use in react router 3, still you can use different ways to push by withRouter or context but i will recommend use withRouter HOC. You should use the withRouter high order component, and wrap that to the component that will push to history. For example:
import React from "react";
import { withRouter } from "react-router-dom";
class MyComponent extends React.Component {
...
myFunction() {
this.props.history.push("/HOME");
}
...
}
export default withRouter(MyComponent);
这篇关于无法读取反应中未定义的属性“推送"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!