简体   繁体   English

如何在成功登录后重定向并在reactjs中阻止页面而无需登录?

[英]how to redirect after successful login and block pages without login in reactjs?

I am using axios to get data and login but after login i need to redirect to dashboard component and prevent going back and block entering without login.我正在使用 axios 获取数据和登录,但登录后我需要重定向到仪表板组件并防止返回并阻止在没有登录的情况下进入。 Currently using window.location.href method but i need in react method.目前使用 window.location.href 方法,但我需要 react 方法。

My login Function is:我的登录功能是:

getLoginDetails(){
    var input = document.getElementById("userInput").value;
    var pass = document.getElementById("userPassword").value;
      axios.post(' http:api here', {
      email:input,
      pin: pass
    })
    .then(function (response) {
      var status = response.data.status;
      if(status === 'success'){
        window.location.href="/dashboard";   
      }else{
        alert("Invalid Userid or Password");
      }
    })
    .catch(function (error) {
      console.log(error);
    });

  }

My button is :我的按钮是:

<Button
          className="login-button"
          color={"#36b0ff"}
          variant="primary"

          onClick={this.getLoginDetails}
        >
          Login
        </Button>

Kindly help me out.Redirect Tag and props are shoeing error.请帮帮我。重定向标签和道具是鞋子错误。

One simple solution would be to check user status in both login and dashboard components (this might not be a good idea if you have a complicated authentication flow).一个简单的解决方案是在登录和仪表板组件中检查用户状态(如果您的身份验证流程复杂,这可能不是一个好主意)。
login component:登录组件:

class Login extends Component{
    componentDidMount(){
        const isLoggedin = checkLogin();
        if(isLoggedin)
            this.props.history.push('/dashboard');
    }
}
export default withRouter(Login)

and your dashboard:和您的仪表板:

class Dash extends Component{
    componentDidMount(){
        const isLoggedin = checkLogin();
        if(!isLoggedin)
            this.props.history.push('/login');
    }
}

considering that you store your token in local storage after user loges in:考虑到您在用户登录后将令牌存储在本地存储中:

checkLogin(){
    //you can retrieve your token and verify it in your own way.
    const token = window.localStorage.getItem('token')
    if(!token)
        return false
    return true
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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