Reactjs - 在函数内重定向 - 不工作

时间:2017-09-29 22:18:09

标签: reactjs

我正在研究reactjs应用程序。我正在创建一个用户登录页面 - 并希望将用户重定向到主页或管理页面 - 取决于他们的角色 - 但我也试图确保如果用户已经登录 - 尝试返回登录页面 - 它们以类似的逻辑反弹回来。

当我尝试将“重定向”部分放在一个函数中时 - 没有任何反应。

这是当前的代码库。

//登录代码

   var isAdmin = false;

    const user = JSON.parse(localStorage.getItem('user'));
    if(!user){

      if(this.props.authData.isLogged){
        const currentUser = JSON.stringify(this.props.authData);
        localStorage.setItem('user', currentUser);

        isAdmin = this.isLoggedInAnAdmin(this.props.authData);
        if(!isAdmin){
          return (
            <Redirect to="/home"/>
          )
        }else{
          return (
            <Redirect to="/admin"/>
          )
        }

      } 

      if(this.props.authData.data){
        //if error from server side show the message
        if(this.props.authData.data.data.status !== "success"){
          errorPlaceholder = this.props.authData.data.data.msg;
        }
      }
    }
    else{
      //redirect to home

      if(user){
        isAdmin = this.isLoggedInAnAdmin(user);
        if(!isAdmin){
          return (
            <Redirect to="/home"/>
          )
        }else{
          return (
            <Redirect to="/admin"/>
          )
        }
      }
    }

但如果我将重定向代码放在自己的函数中 - 它永远不会重定向?

  redirectUser(isAdmin){
        if(!isAdmin){
          return (
            <Redirect to="/home"/>
          )
        }else{
          return (
            <Redirect to="/admin"/>
          )
        }
  }

这是登录shell - 因此它会检查存储或从用户localstorage读取。

import React, { Component } from 'react'
import { NavLink, withRouter, Redirect } from 'react-router-dom';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { fetchAuthentication } from '../../actions/authAction';

import {persistStore} from 'redux-persist'

import { Row, Col } from 'antd';

// components
import LoginSyncValidationForm from './LoginSyncValidationForm'

import '../../forms.scss';

// this is a class because it needs state
class Login extends Component {

  constructor(props, context) {
    super(props, context);
    this.submit = this.submit.bind(this);
  }

  /*
  static propTypes = {
    isDark: React.PropTypes.bool
  }
  static defaultProps = {
    isDark: false
  }
  */

  componentDidMount() {
    //document.body.classList.toggle('darkClass', this.props.isDark)
  }
  componentWillReceiveProps(nextProps) {
    //document.body.classList.toggle('darkClass', nextProps.isDark)
  }

  componentWillMount () {
    document.body.classList.add('screenbackground');
  }

  componentWillUnmount() {
    document.body.classList.remove('screenbackground');
  }

  isLoggedInAnAdmin(user){
    //redirect if logged in already
    console.log("REDIRECT----", user);

      var isAdmin = false;
      if(user.data.data.data[0].role === "1"){
        isAdmin = true;
      }

      console.log("isAdmin----", isAdmin);
      return isAdmin;
  }

  redirectUser(isAdmin){

  }

  submit(data) {
    this.props.fetchAuthentication(data);
  }

  render() {
    // save object to localstorage as a string but you fetch it as a string
    // JSON.stringify(toLocalStorage) ============ JSON.parse(fromLocalStorage);
    // when the user has logged in - navigate them to the home page

    var errorPlaceholder = "";
    var isAdmin = false;

    const user = JSON.parse(localStorage.getItem('user'));
    //console.log("user already logged in", user);
    if(!user){

      if(this.props.authData.isLogged){
        //return <Redirect to='/home'/>;
        const currentUser = JSON.stringify(this.props.authData);
        localStorage.setItem('user', currentUser);
        //persistor.rehydrate()//calls reducer to rehydrate store

        isAdmin = this.isLoggedInAnAdmin(this.props.authData);
        if(!isAdmin){
          console.log("redirect y");
          return (
            <Redirect to="/home"/>
          )
        }else{
          console.log("redirect x");
          return (
            <Redirect to="/admin"/>
          )
        }

      } 

      if(this.props.authData.data){
        //if error from server side show the message
        if(this.props.authData.data.data.status !== "success"){
          errorPlaceholder = this.props.authData.data.data.msg;
        }
      }
    }
    else{
      //redirect to home
      //console.log("rediret to home");
      //const user = JSON.parse(localStorage.getItem('user'));
      console.log("user already logged in", user);
      console.log("LOGIN -- user", user);

      if(user){
        isAdmin = this.isLoggedInAnAdmin(user);
        if(!isAdmin){
          console.log("redirect y");
          return (
            <Redirect to="/home"/>
          )
        }else{
          console.log("redirect x");
          return (
            <Redirect to="/admin"/>
          )
        }
      }
    }


    return (
      <div className="Page form-components light">
        <h2>Login</h2>
        <Row>
          <Col xs={24} sm={24} md={10}>
            <p>Welcome to the SLAM SDQ tracker. Because you're accessing sensitive information, you need to confirm your identity using our secure login system. Your unique identification number has been sent to you by e-mail, please use it to login below.</p>
          </Col>
          <Col xs={24} sm={24} md={24}>
            <Row>
              <Col xs={24} sm={24} md={24}>
                <LoginSyncValidationForm onSubmit={this.submit} />
              </Col>
              <Col xs={24} sm={24} md={6}>
                <p><NavLink to="/forgot-password" activeClassName="selected">Forgotten your password?</NavLink> Not created an account yet? <NavLink to="/register-user" activeClassName="selected">Sign up</NavLink></p>
              </Col>
            </Row>
          </Col>
          {errorPlaceholder.length > 0 &&
            <Col xs={24} sm={24} md={12}>
              {errorPlaceholder}
            </Col>
          }
        </Row>
        <div className="shell" />
        <div className="screen-background login"/>
      </div>
    )
  }

}

function mapStateToProps(state) {
  return {
    authData: state.auth
  };
}

function mapDispatchToProps(dispatch) {
 return bindActionCreators({ fetchAuthentication }, dispatch);
}

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Login))

0 个答案:

没有答案