简体   繁体   English

this.props.history.push 未定义

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

I am creating a form with some predefined values, and i want to route to the dashboard page once the form is submitted.我正在创建一个带有一些预定义值的表单,我想在提交表单后路由到仪表板页面。 I am using handleLoginSubmit func on the onsubmit of the form.我在表单的 onsubmit 上使用 handleLoginSubmit func。 For that, I have the following code:为此,我有以下代码:

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


};

But, I am receiving the error saying that history is undefined.但是,我收到错误消息说历史未定义。 Please help me out here请帮帮我

You need to export the component with router to access history您需要使用路由器导出组件才能访问历史记录

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

export default withRouter(ComponentName)

if your component is linked with Route then you can directly access that in this.props but if its sub-component or children of some component then you cant access it into this.props .如果您的组件与Route链接,那么您可以直接在this.props中访问它,但如果它的子组件或某个组件的子组件则您无法访问它到this.props中。

so there is multiple way to solve it所以有多种方法可以解决

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

export default withRouter(Component)
  1. use useHistory hook and save it to constant ( functional component )使用useHistory挂钩并将其保存到常量(功能组件)
import { useHistory } from 'react-router-dom';

const history = useHistory();

Update of Nisharg Shah's answers of part 3 for future reference.更新Nisharg Shah 对第 3 部分的回答以供将来参考。

If you are using react-router-dom v6 , then use useNavigate instead of useHistory .如果您使用的是react-router-dom v6请使用 useNavigate 而不是 useHistory

You can use:您可以使用:

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

let navigate = useNavigate();

OR要么

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