繁体   English   中英

this.props.history.push 未定义

[英]this.props.history.push is undefined

我正在创建一个带有一些预定义值的表单,我想在提交表单后路由到仪表板页面。 我在表单的 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");
}


};

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

您需要使用路由器导出组件才能访问历史记录

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

export default withRouter(ComponentName)

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

所以有多种方法可以解决

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

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

const history = useHistory();

更新Nisharg Shah 对第 3 部分的回答以供将来参考。

如果您使用的是react-router-dom v6请使用 useNavigate 而不是 useHistory

您可以使用:

import { useNavigate } from "react-router-dom";

let navigate = useNavigate();

要么

import { useNavigate } from "react-router-dom";

function App() {
  let navigate = useNavigate();
  function handleClick() {
    navigate("/home");
  }
  return (
    <div>
      <button onClick={handleClick}>go home</button>
    </div>
  );
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM