ReactJS 使用重定向登录(如果经过身份验证)



我正在尝试将一个简单的登录系统与Laravel后端放在一起。

我有:

登录.js

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
export default class Login extends Component {
    componentWillMount() {
        // do something like setting default state
    }
    processSubmit(values) {
        // do something with the values
    }
    render() {
        const { handleSubmit, submitting } = this.props;
        return (
            <div className="container mt-5">
                <div className="row justify-content-center">
                    <div className="col-6">
                        <div className="card">
                            <div className="card-body">
                                <h2 className="text-center font-weight-light mb-4">Sign into your account</h2>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        );
    }
};

成功登录后,重定向到仪表板...

仪表板.js

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
export default class Dashboard extends Component {
    render() {
        return <div>
        </div>
    }
}

应用.js

import React, {Component} from 'react'
import ReactDOM from 'react-dom'
import {BrowserRouter, Route, Switch} from 'react-router-dom'
import Home from '../containers/Home';
import Login from '../containers/LogIn';
import CreateUsers from '../containers/CreateUsers';
import Dashboard from '../containers/Dashboard';
import NavBar from './NavBar';
class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            isAuthenticated: false
        };
    }
    userHasAuthenticated = authenticated => {
        this.setState({isAuthenticated: authenticated});
    };
    render() {
        return (
            <BrowserRouter>
                <div>
                    <NavBar />
                    <Route exact path="/" component={Home}/>
                    <Route path="/login" component={Login}/>
                    <Route path="/users/create" component={CreateUsers}/>
                    <Route path="/dashboard" component={Dashboard}/>
                </div>
            </BrowserRouter>
        )
    }
}
ReactDOM.render(<App />, document.getElementById('app'))

如果用户未经身份验证,我如何让它将用户重定向到登录页面,并且如果他们将用户发送到仪表板/主页,则相同?

在您的componentDidMount()constructor()中,尝试执行fetch(),看看当前会话是否处于活动状态。如果会话处于活动状态,请通过调用以下命令将会话设置为 true:

this.userHasAuthenticated(true);

像这样的东西可能会起作用:

constructor(props) {
  super(props);
  this.state = {
    isAuthenticated: false
  };
  fetch("/api/isUserLoggedIn")
  .then(function(response) {
    return response.json();
  })
  .then(function(res) {
    if (res == true) {
      this.userHasAuthenticated(true);
      // Redirect the user only if they are on the login page.
      // So the below code should be there only on the login component.
      this.props.history.push("/dashboard");
    }
  });
}

ps:这就是我们在应用程序中的做法。 😇

相关内容

最新更新