简体   繁体   中英

Can't redirect after login React-Redux

I'm relatively new to React and Redux, and I'm trying to manage a login system and authenticated routes. I currently have a login form that calls an action called login on submit, which changes the redux state to have isAuthenticated set to true and user set to whatever the user is.

I want to redirect the user back to the previous page from wherever they are logging in from, but when I log in, it gets redirected back to the home page before I get the chance to change the state of the login form to redirect back to referral, the component gets unmounted.

The code for the login form and login redux action is shown below. Thanks in advance for your help.

 class LoginForm extends Component { constructor(props) { super(props); this.state = { email: '', password: '', errors: {}, redirectToReferrer: false }; this.onChange = this.onChange.bind(this); this.onSubmit = this.onSubmit.bind(this); this.login = login.bind(this); } onChange(e){ this.setState({[e.target.name]: e.target.value}); } onSubmit(e) { e.preventDefault(); const post = { email: this.state.email, password: this.state.password } this.props.login(post).then( (res) => this.setState(() =>{redirectToReferrer: true}), (err) => console.log(err) ) } render(){ const { redirectToReferrer } = this.state.redirectToReferrer; const { from } = {from: {pathname: '/client/games'}}; if(redirectToReferrer === true){ return( <Redirect to={from} /> ) } return( <div> <form onSubmit={this.onSubmit}> <input type="text" id="email" onChange={this.onChange} name="email" placeholder="Email"/> <input type="password" id="password" onChange={this.onChange} name="password" placeholder="Password"/> <br /> <button type="submit" className="submit">Login</button> </form> <br /> </div> ); } } LoginForm.contextTypes = { router: PropTypes.object.isRequired } LoginForm.propTypes = { from: PropTypes.object.isRequired } export default connect(null, { login })(LoginForm); 

 export function setCurrentUser(token) { //action function to set user from given jwtToken return { type: SET_CURRENT_USER, user: token.user } } export function login(data) { return dispatch => { return axios.post('/users/login', data) //post login info to backend .then(res => { const token = res.data.token; //get the token from the response localStorage.setItem('jwtToken', token); //set the jwtToken dispatch(setCurrentUser(JWT.decode(token, 'authtoken'))); //dispatch currentUser action with the given decoded token }) } } 

I'm not entirely sure that we're using the same react-router. But I usually use push in my setup.

import { push } from "react-router-redux";

export const changeUrl = location => dispatch => dispatch(push(location));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM