首页 > 解决方案 > 无法读取登录页面上未定义的属性“推送”

问题描述

我正在使用 JWT 做一个登录页面,并尝试使用 this.props.history.push("/") 登录到主页后重定向该页面,但我得到这个 typeError: Cannot read property 'push'of undefined。我不知道我做错了什么。

class Login extends Component {
  constructor(props) {
      super(props);
      this.state = {
          email: "cihemzine@gmail.com",
          password: "test",
      };
  }

  handleChange = (e) => {
      this.setState({
          [e.target.name]: e.target.value,
      });
  };

  login = () => {
      const { email, password} = this.state;
      axios("/users/login", {
          method: "POST", 
          data: {
              email,
              password
          },
      })
      .then((response) => {
        localStorage.setItem('token', response.data.token);
        
          console.log(response.data);
          this.props.history.push("/");
          
      })
      .catch((error) => {
          console.log(error);
      });

  };
    
    render() {
        return (
            <div>
             <div className="container">
                
        <input  value={this.state.email} onChange={this.handleChange} className="form-control mb-2 mt-4"name="email" type="text"placeholder="Your email" />
        <input value={this.state.password} onChange={this.handleChange} className="form-control mb-2"name="password" type="password" placeholder="Your password" /><br></br>
        <button onClick={this.login}className="text-center btn btn-light">LOGIN</button>
            </div>
            </div>
        )
    }
}


export default Login;

标签: javascriptreactjsauthenticationerror-handlingtypeerror

解决方案


如果您的道具中没有类似“历史、匹配等”的内容,您需要检查您是否将登录组件用作路由

<Route path ='' component={Login} />

如果您不以这种方式使用登录并且由于某些原因不能。您可以使用 HOC 或钩子为您的组件添加历史记录到您的组件。

import { useHistory } from "react-router-dom"
or
import { withRouter } from "react-router";

推荐阅读