无法读取反应中未定义的属性“push”

2024-03-31

    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>
    )
  }
}

我在控制台中收到 Cannot read property 'push' of undefined 的消息。现在如何访问react-router v4中的推送。

提前致谢!


默认情况下,不能在 React router 4 中使用 browserHistory,因为您可以在 React router 3 中使用,您仍然可以使用不同的方式通过 withRouter 或 context 进行推送,但我会推荐 与路由器 HOC 一起使用。 您应该使用 withRouter 高阶组件,并将其包装到将推送到历史记录的组件。例如:

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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

无法读取反应中未定义的属性“push” 的相关文章

随机推荐