this.props.history.push 未定义

问题描述

我正在创建一个带有一些预定义值的表单,我想在提交表单后路由到仪表板页面。我在表单的 onsubmit 上使用 handleLoginSubmit func。为此,我有以下代码

handleLoginSubmit = (e) => {
e.preventDefault();
let hardcodedCred = {
  email: "email@email.com",password: "password123",};

if (
  this.state.email == hardcodedCred.email &&
  this.state.password == hardcodedCred.password
) {
  //combination is good. Log them in.
  //this token can be anything. You can use random.org to generate a random string;
  // const token = "123456abcdef";
  // sessionStorage.setItem("auth-token",token);
  //go to www.website.com/todo
  // history.push("/dashboard");
  this.props.history.push("/dashboard");

  // console.log(this.state.route);
  console.log(this.context);
  console.log("logged in");

  // <Link to={location} />;
} else {
  //bad combination
  alert("wrong email or password combination");
}


};

但是,我收到错误消息,指出历史未定义。 请帮帮我

解决方法

如果您的组件与 Route 链接,那么您可以直接在 this.props 中访问它,但如果它的子组件或某个组件的子组件,则您无法在 this.props 中访问它。

所以有多种方法可以解决它

  1. 如果组件与 Route 链接,则在组件中将历史作为道具传递
<Component history={this.props.history} />
  1. 使用 withRouter HOC,绑定组件中的所有 Route props
import { withRouter } from 'react-router-dom';

export default withRouter(Component)
  1. 使用 useHistory 钩子并将其保存到常量(功能组件)
import { useHistory } from 'react-router-dom';

const history = useHistory();
,

需要用router导出组件才能访问历史

import { withRouter } from 'react-router-dom';

export default withRouter(ComponentName)