gpt4 book ai didi

javascript - 无法读取登录页面上未定义的属性 'push'

转载 作者:行者123 更新时间:2023-12-03 08:18:08 25 4
gpt4 key购买 nike

我正在使用 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;

最佳答案

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

<Route path ='' component={Login} />
如果您不以这种方式使用登录并且由于某些原因不能。
您可以使用 HOC 或钩子(Hook)为您的组件添加历史记录到您的组件。
import { useHistory } from "react-router-dom"
or
import { withRouter } from "react-router";

关于javascript - 无法读取登录页面上未定义的属性 'push',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63331435/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com