假设用户想要查看需要身份验证的页面。成功登录后,我希望用户首先被重定向到他/她想要查看的页面。
这是登录组件:
import React, { Component } from 'react';
import { Field, reduxForm } from 'redux-form';
import { connect } from 'react-redux';
import { loginUser } from '../actions';
import validator from 'validator';
class LoginForm extends Component {
renderField(field) {
const {meta: {touched, error}} = field;
const className = `form-group ${touched && error ? 'has-danger':''}`;
return (
<div className={className}>
<label>{field.label}</label>
<input className="form-control"
type="text"
{...field.input}
/>
<div className="text-help">
{touched ? error:''}
</div>
</div>
);
}
onSubmit(values) {
const { history } = this.props;
this.props.loginUser(values, ({status, headers}) => {
if (status === 200) {
const { authorization } = headers;
localStorage.setItem('jwt_token', authorization);
history.push("/"); //HERE ????
}
});
}
render() {
if (localStorage.getItem('jwt_token')) {
this.props.history.push("/");
}
const {handleSubmit} = this.props;
return (
<form onSubmit={handleSubmit(this.onSubmit.bind(this))}>
<Field
name="username"
label="Username"
component={this.renderField}
/>
<Field
name="password"
label="Password"
component={this.renderField}
/>
<button type="submit" className="btn btn-primary">Enter</button>
</form>
);
}
}
function validate(values) {
//.....
}
export default reduxForm({
validate,
form:'LoginForm'
})(
connect(null, { loginUser })(LoginForm)
);
我尝试了history.goBack()
,但显然在转到登录页面之前,它没有重定向到用户想要访问的路径。我该怎么办?
答案 0 :(得分:0)
我认为你的逻辑错了!
withRouter
用户访问history.push()
方法
import { withRouter } from 'react-router-dom';
import axios from 'axios';
@withRouter
class LoginForm extends Component {
** DidMount because it's client side and you reading the token from window ojbect **
componentDidMount() {
I don't know you use which library to handle request...
const token = localStorage.getItem('jwt_token');
if (token) {
axios.get('/user/profile', {
header: {
token
}
})
.then((response) => {
this.props.history.push('/');
})
.catch((error) => {
// 401 Unauthorized
});
}
}
}