我已经用JWT制作并获取了一个Login表单,然后做出了反应。我设法获取了用户名和密码的数据,并且一切正常,但是当他单击“提交”时,我想将用户重定向到新页面,我不知道该怎么做。我也在使用反应路由器。任何帮助都将受到欢迎
import React, { Component } from "react";
import axios from "axios";
export default class Login extends Component {
constructor(props) {
super(props);
this.state = {
username: "test",
password: "test",
}
}
handleChange = (e) => {
this.setState({
[e.target.name]: e.target.value,
})
}
login = () => {
const {username, password} = this.state;
axios(`/users/login`, {
method: "POST",
data: {
username,
password,
}
})
.then(response => {
localStorage.setItem('token', response.data.token);
console.log(response);
})
.catch(error => {
console.log(error)
})
}
render() {
return (
<div className="log">
<h3>Sign In</h3>
<div className="form-group">
<label>Username</label>
<input type="username" className="form-control" placeholder="Enter username" name="username" value={this.state.username} onChange={this.handleChange} />
</div>
<div className="form-group">
<label>Password</label>
<input type="password" className="form-control" placeholder="Enter password" name="password" value={this.state.password} onChange={this.handleChange} />
</div>
<div className="form-group">
<div className="custom-control custom-checkbox">
<input type="checkbox" className="custom-control-input" id="customCheck1" />
<label className="custom-control-label" htmlFor="customCheck1">Remember me</label>
</div>
</div>
<button type="submit" className="btn btn-primary btn-block" onClick={this.login}>Submit</button>
<p className="forgot-password text-right">
Forgot <a href="#">password?</a>
</p>
</div>
);
}
}
答案 0 :(得分:1)
使用路由器import {withRouter} from 'react-router-dom';
在课程登录export
之前删除class Login extends Component {...
导出类位于文件末尾:export default withRouter(Login);
并使用react-router-dom:
axios(`/users/login`, {
//...
})
.then(response => {
localStorage.setItem('token', response.data.token);
console.log(response);
this.props.history.push('/url');
})
//...