簡體   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