从登录页面导航到所需的页面

时间:2017-12-17 12:16:57

标签: reactjs react-router

假设用户想要查看需要身份验证的页面。成功登录后,我希望用户首先被重定向到他/她想要查看的页面。

这是登录组件:

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(),但显然在转到登录页面之前,它没有重定向到用户想要访问的路径。我该怎么办?

1 个答案:

答案 0 :(得分:0)

我认为你的逻辑错了!

  1. 您应该使用react life cycles并发送请求 后端如果你获得用户信息,你可以重定向到索引路由。
  2. 您应该从withRouter用户访问history.push() 方法
  3. 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
        });
        }
      }
    
    }