javascript - 无法读取登录页面上未定义的属性“推送”
问题描述
我正在使用 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;
解决方案
如果您的道具中没有类似“历史、匹配等”的内容,您需要检查您是否将登录组件用作路由
<Route path ='' component={Login} />
如果您不以这种方式使用登录并且由于某些原因不能。您可以使用 HOC 或钩子为您的组件添加历史记录到您的组件。
import { useHistory } from "react-router-dom"
or
import { withRouter } from "react-router";
推荐阅读
- javascript - 为什么我可以使用 [1] 而不是 [one] 创建属性?
- gatling - 无法在请求中从 Feeder 文件传递值
- r - 使用函数参数作为数据帧的名称,使用超级赋值 <<-
- android - (方法 Glide.with(android.content.Context) 不适用)
- azure-functions - DurableEntity - 模拟 SignalEntityAsync
- single-sign-on - 客户端使用 https 时,Keycloak 重定向 uri 无效
- azureservicebus - 偷看后如何从队列中删除消息?
- android - Kotlin 中的 Android 自定义 Spinner
- android - Android中的Hilt依赖注入仪器测试
- c# - .net 上的自定义验证