简体   繁体   English

如何在ReactJS + REDUX中输入索引路径之前重定向到登录页面

[英]How To Redirect to Login Page Before Entering Index Route in ReactJS + REDUX

I am really new to react, now i want to implement a login page before entering to any routes, i am currently using : 我真的很新做出反应,现在我想在进入任何路线之前实施登录页面,我目前正在使用:

React : 15.4.2, React-DOM : 15.4.2, React-Redux : 5.0.4, and i am using webpack and es2015 as my preset. React:15.4.2,React-DOM:15.4.2,React-Redux:5.0.4,我使用webpack和es2015作为我的预设。

i have done so much googling, but i still does not found any solution, here is current source code : for index.js : 我已经做了很多谷歌搜索,但我仍然没有找到任何解决方案,这里是当前的源代码:for index.js:

import React from "react";
import ReacrDOM from "react-dom";
import {Router, Route, IndexRoute, hashHistory} from "react-router"
import {Provider} from "react-redux";

import store from "./store";
import Layout from "./pages/Layout";
import Dashboard from "./pages/Dashboard";
import Login from "./pages/login/index";
import User from "./pages/user/index";
import EnsureLoggedIn from "./EnsureLoggedIn";

const app = document.getElementById("app");

ReacrDOM.render(
    <Provider store={store}>
        <Router history={hashHistory}>
            <Route path="/login" component={Login}/>
            <Route component={EnsureLoggedIn}>
                <Route path="/" component={Layout}>
                    <IndexRoute component={Dashboard}/>
                    <Route path="user" component={User}/>
                </Route>
            </Route>
        </Router>
    </Provider>
    , app);

Here is my Dashboar Component : 这是我的Dashboar组件:

import React from "react";
import {connect} from "react-redux";

@connect((store) => {
    return {

    }
})

export default class Dashboard extends React.Component {

    componentWillMount() {

    }

    render() {
        return (
            <div>
                <h3>Dashboard</h3>
                <hr/>
            </div>
        );
    }
}

and here is my EnsureLoggedIn File : 这是我的EnsureLoggedIn文件:

import React from "react";
import {browserHistory} from 'react-router';
import {connect} from "react-redux";
import {login_check, show_log} from "./actions/logActions";

@connect((store) => {
    return {
        session_key: store.logReducer.session_key,
        user_id: store.logReducer.user_id,
        error_message: store.logReducer.error_message,
        logged_in: store.logReducer.logged_in
    }
})


export default class EnsureLoggedIn extends React.Component {
    componentDidMount() {

        if (!this.isLoggedIn()) {
            browserHistory.push('#/login');
        }
    }

    isLoggedIn() {
        this.props.dispatch(show_log());
        var account = {user_id: this.props.user_id, session_key: this.props.session_key};
        this.props.dispatch(login_check(account));
        if (!this.props.logged_in) {
            return false;
        }

        return true;
    }

    render() {
        return this.props.children
    }
}

and here is my logReducer : 这是我的logReducer:

export default function (state = {
    user_id: null,
    session_key: null,
    error_message: null,
    logged_in: false,
    log_error: null,
}, action) {

    switch (action.type) {
        case "LOGIN": {
            var {id, session_key}=action.payload.data.data
            state = {
                ...state,
                user_id: id,
                session_key,
                error_message: null,
                logged_in: true,
                log_error: null
            };
            break;
        }

        case "LOGIN_FAILED": {
            state = {
                ...state,
                error_message: null,
                log_error: action.payload.response.data.error.message,
                logged_in: false
            };
            break;
        }

        case "CHECK_LOGIN": {
            state = {...state, error_message: null, logged_in: true};
            break;
        }

        case "CHECK_LOGIN_FAILED": {
            state = {
                ...state,
                error_message: action.payload.response.data.error.message,
                log_error: null,
                logged_in: false
            };
            break;
        }

        case "LOGOUT": {
            state = {
                ...state,
                user_id: null,
                session_key: null,
                error_message: null,
                log_error: null,
                logged_in: false
            };
            break;
        }

        case "GET_LOG_DATA": {
            state = {...state};
            break;
        }

    }

    return state;
}

and this is my logActions file : 这是我的logActions文件:

import axios from "axios";

const basicAuth = {
    headers: {"authorization": "Basic dmlkeTpwdmlkeQ=="}
}

export function login(email = "", password = "") {
    var url = 'http://localhost:8080/dfordatabase/api/api/login';
    return function (dispatch) {
        axios.post(url, {email: email, password: password}, basicAuth)
            .then((response) => {
                dispatch({type: "LOGIN", payload: response});
            }).catch((error) => {
            dispatch({type: "LOGIN_FAILED", payload: error});
        })
    }
}

export function login_check(account = {}) {
    var url = 'http://localhost:8080/dfordatabase/api/api/login_check';
    return function (dispatch) {
        axios.post(url, {...account}, basicAuth)
            .then((response) => {
                dispatch({type: "CHECK_LOGIN", payload: response});
            }).catch((error) => {
            dispatch({type: "CHECK_LOGIN_FAILED", payload: error});
        })
    }
}

export function show_log() {

    return function (dispatch) {
        dispatch({type: "GET_LOG_DATA", payload: null});
    }
}

the problem is : indeed login page will appear at first when i run the code, but when i fill the credential and logged in, page is not redirect to my index route which is "/", the url has change, but dashboard won't appear, if i refresh the page dashboard appear but, the problem is all state of my log reducer become empty again. 问题是:当我运行代码时,确实会首先出现登录页面,但是当我填写凭证并登录时,页面不会重定向到我的索引路由,即“/”,网址已更改,但仪表板赢了“ t出现,如果我刷新页面仪表板但是,问题是我的日志缩减器的所有状态再次变为空。

can anyone tell me where can i find some example of similar development tutorial. 谁能告诉我在哪里可以找到类似开发教程的一些例子。 Please kindly help me.. 请帮助我..

The property onEnter has been removed since react-router-4 , now you should use the render method instead, here's an example how to do a redirect : 反应路由器4之后已删除属性onEnter ,现在你应该使用render方法,这里是一个如何进行重定向的示例:

<Route exact path="/home" render={(props) => (
  isUserLoggedIn() ? (
    <Home {...props} />
  ) : (
    <Redirect to="/login"/>
  )
)}/>

You need to implement OnEnter props in the routers. 您需要在路由器中实现OnEnter道具。 Check this project for the whole sollutions: React Redux Universal Hot Example 检查此项目的整个解决方案: React Redux Universal Hot Example

Thanks alot Dat Tran, now i just change my index.js code into this : 非常感谢Dat Tran,现在我只需将index.js代码更改为:

import React from "react";
import ReacrDOM from "react-dom";
import {Router, Route, IndexRoute, hashHistory, browserHistory} from "react-router"
import {Provider} from "react-redux";
import {login_check, show_log, fakeLogin} from "./actions/logActions";

import store from "./store";
import Layout from "./pages/Layout";
import Dashboard from "./pages/Dashboard";
import Login from "./pages/login/index";
import User from "./pages/user/index";
import Pemain from "./pages/pemain/index";

const app = document.getElementById("app");

function requireLogin() {
    const {user_id, session_key}=store.getState().logReducer;
    store.dispatch(login_check({user_id: user_id, session_key: session_key}))
    const {logged_in}=store.getState().logReducer;
    if (!logged_in) {
        browserHistory.push('#/login');
        hashHistory.push('/login');
    }
}

ReacrDOM.render(
    <Provider store={store}>
        <Router history={hashHistory}>
            <Route path="/login" component={Login}/>
            <Route path="/" component={Layout} onEnter={requireLogin}>
                <IndexRoute component={Dashboard}/>
                <Route path="user" component={User}/>
                <Route path="pemain" component={Pemain}/>
            </Route>
        </Router>
    </Provider>
    , app);

and my login.js into this : 和我的login.js到这个:

import React from "react";
import {connect} from "react-redux";
import {login} from "../../actions/logActions";
import {browserHistory, hashHistory} from "react-router"

@connect((store) => {
    return {
        session_key: store.logReducer.session_key,
        user_id: store.logReducer.user_id,
        error_message: store.logReducer.error_message,
        logged_in: store.logReducer.logged_in,
        log_error: store.logReducer.log_error,
    }

})

export default class index extends React.Component {

    login(event) {
        event.preventDefault();
        this.props.dispatch(login(this.refs.email_pemain.value, this.refs.password.value));
    }

    showError() {
        if (this.props.log_error) {
            return (
                <div className="error_message alert-danger">
                    {this.props.log_error}
                </div>
            );
        }

        return (<div>

        </div>);
    }


    render() {

        if (this.props.logged_in) {
            browserHistory.push('#/');
            hashHistory.push('/');
        }

        return (
            <div className="container">
                <div className="login-box">
                    <div className="header">
                        login
                    </div>
                    <div className="login-form-wrapper">
                        <form onSubmit={this.login.bind(this)}>
                            <div>
                                <label for="email_pemain">Email</label>
                                <input className="form-control" id="email_pemain" name="email_pemain" type="text"
                                       ref="email_pemain"/>
                            </div>
                            <div>
                                <label for="password">Password</label>
                                <input className="form-control" id="password" name="password" type="password"
                                       ref="password"/>
                            </div>
                            <br/>
                            <br/>
                            <input className="btn btn-info pull-right" type="submit" value="Login"/>
                            <div className="clearfix">

                            </div>
                            {this.showError()}
                        </form>
                    </div>
                </div>
            </div>
        );
    }
}

and it works now...and thank you very much @Dat Tran 它现在有效......非常感谢@Dat Tran

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

相关问题 如何使用 ReactJS 将登录页面重定向到仪表板? - How to redirect login page to dashboard using ReactJS? 登录后如何重定向到主页:ReactJS? - how to redirect to home page after login: ReactJS? 登录成功后如何重定向到一个页面:ReactJS? - how to redirect to a page after successful login: ReactJS? ReactJS成功登录后如何重定向到页面? - how to redirect to a page after successful login in ReactJS? 如何在 ReactJS 中登录页面后重定向/转到用户配置文件 - How to Redirect/go to the User Profile after login page in ReactJS ReactJS:本地存储需要时间来存储令牌,并且登录页面无法首次重定向到仪表板路由 - ReactJS: Local Storage taking time to store token, and login page is unable to redirect first time to dashboard route 输入错误的用户名和/或密码后,如何将用户从登录控件重定向到错误页面? - How to redirect user to an error page from login control upon entering wrong username and/or password? ReactJS身份验证不起作用,重定向到登录页面失败 - ReactJS auth not working, redirect to login page fails 重新提交前最初显示的登录页面-Reactjs - Login page showing initiially before rerender - Reactjs 密码不匹配时,如何在多重登录中重定向到索引页面 - how to redirect to index page in multi login when password does not match
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM