this.props.history.push 未定义

Ade*_*iya 1 history push reactjs react-router

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

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


};
Run Code Online (Sandbox Code Playgroud)

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

Sin*_*man 5

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

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

export default withRouter(ComponentName)
Run Code Online (Sandbox Code Playgroud)


Nis*_*hah 5

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

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

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

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

const history = useHistory();
Run Code Online (Sandbox Code Playgroud)