首页 >web前端 >js教程 >React如何实现登录?react登录模块的详解

React如何实现登录?react登录模块的详解

寻∝梦
寻∝梦原创
2018-09-11 16:29:406957浏览

本篇文章主要的介绍了关于react的登录模块,详细的介绍了关于react的登录情况。现在就让我们一起来看看文章的正文吧

基于React的登录

第一种登录

  • Login页面提交登录 handleSubmit(), 中直接调用API请求。请求登录成功后跳转 history.push(nextPathname, null);

  • 实现方式参照 http://blog.csdn.net/qq_27384769/article/details/78775835

第二种登录

  • Login页面提交登录 handleSubmit() 后,通过saga发起异步请求。

  • 请求成功后 发起action 调用reducer. 重新加载Login页面。

  • 在Login页面生命周期componentWillReceiveProps 验证登录信息请求跳转。

以下是第二种登录方式的讲解

reducer 中的数据结构

auth:{
	type: "COMPLOGIN/RECEIVE_DATA", 
	isFetching: false, 
	data: {uid: 1, permissions: Array(5), role: "系统管理员", roleType: 1, userName: "系统管理员"}
}

代码

login.jsx

  • componentWillReceiveProps 登录成功后 调整

  • handleSubmit 处理提交登录

import React from 'react';import {Form, Icon, Input, Button, Checkbox} from 'antd';import {connect} from 'react-redux';import {bindActionCreators} from 'redux';import {findData, receiveData} from '../actions';import {selectVisibleMenuResourceTreeTable} from '../selector';const FormItem = Form.Item;class Login extends React.Component {    componentWillMount() {        const {receiveData} = this.props;        receiveData(null, 'auth');
    }    componentWillReceiveProps(nextProps) {        const {auth: nextAuth = {}} = nextProps;        if (nextAuth.data && nextAuth.data.uid) {   // 判断是否登陆
            localStorage.setItem('user', JSON.stringify(nextAuth.data));            this.props.history.push('/', null);
        }
    }    handleSubmit = (e) => {        e.preventDefault();        this.props.form.validateFields((err, values) => {            if (!err) {                console.log('Received values of form: ', values);                const {findData} = this.props;                if (values.userName === 'admin' && values.password === 'admin') findData({
                    funcName: 'admin',
                    stateName: 'auth'
                });                if (values.userName === 'guest' && values.password === 'guest') findData({
                    funcName: 'guest',
                    stateName: 'auth'
                });
            }
        });
    };    gitHub = () => {        console.log("gitHub");
    };    render() {        const {getFieldDecorator} = this.props.form;        return (            434e1358c9378ac3fd33b911e780149e
                b2394c444f081e0017d1642dfc84f1f8
                    c92ea6d2badfaeb250216ed853bbdbb2
                        45a2772a6b6107b401db3c9b82c049c2React Admin54bdf357c58b8a65c66d7c19c8e4d114
                    94b3e26ee717c64999d7867364b1b4a3
                    184b34f4f105d6516fe712766a9e325a
                        b991a1338e3038b10035bb6940ac6193
                            {getFieldDecorator('userName', {
                                rules: [{required: true, message: '请输入用户名!'}],
                            })(                                501c34e1e18ea140ee629fc657f756aa}
                                       placeholder="管理员输入admin, 游客输入guest"/>
                            )}                        ef807bb895304b2f6a1f66b2641ea569
                        b991a1338e3038b10035bb6940ac6193
                            {getFieldDecorator('password', {
                                rules: [{required: true, message: '请输入密码!'}],
                            })(                                a702425267d3239dc21f20d5c644eaaf} type="password"
                                       placeholder="管理员输入admin, 游客输入guest"/>
                            )}                        ef807bb895304b2f6a1f66b2641ea569
                        b991a1338e3038b10035bb6940ac6193
                            {getFieldDecorator('remember', {
                                valuePropName: 'checked',
                                initialValue: true,
                            })(                                69393f9a46ae20607b893bed10218172记住我fc4d79e34ad347b99c684660ce4ccba3
                            )}                            cca3a973c05f7502e090180a02c32514忘记密码5db79b134e9f6b82c0b36e0489ee08ed
                            95b3f5ad236f0c0143abd915a9cd3964
                                登录                            a1cb88e6789f399807801ea3799938af
                            或 6170e8999ab19ec641e0422470b16d5c现在就去注册!5db79b134e9f6b82c0b36e0489ee08ed
                            e388a4556c0f65e1904146cc1a846bee
                                7baa8ae66257a5658535c02e56eb333a(第三方登录)                            94b3e26ee717c64999d7867364b1b4a3
                        ef807bb895304b2f6a1f66b2641ea569
                    70a2c5d410e290aa58cb7e59d41eaf55
                94b3e26ee717c64999d7867364b1b4a3
            94b3e26ee717c64999d7867364b1b4a3
        );
    }
}const mapStateToPorps = state => {    return {
        auth: selectVisibleMenuResourceTreeTable(state)
    }
};const mapDispatchToProps = dispatch => ({
    findData: bindActionCreators(findData, dispatch),
    receiveData: bindActionCreators(receiveData, dispatch)
});export default Form.create()(connect(mapStateToPorps, mapDispatchToProps)(Login));

actions

  • findData 点击按钮发起请求

  • requestData 调用API前

  • requestData 调用API 获取到数据

import * as type from './actionTypes';export const findData = (data) => {    let {funcName, stateName} = data;    return {
        type: type.COMP_LOGIN_FIND_DATA,
        funcName,
        stateName
    }
}export const requestData = category => ({
    type: type.COMP_LOGIN_REQUEST_DATA,
    category
});export const receiveData = (data, category) => ({
    type: type.COMP_LOGIN_RECEIVE_DATA,
    data,
    category
});

actionTypes

export const COMP_LOGIN_FIND_DATA = 'COMPLOGIN/FIND_DATA';export const COMP_LOGIN_REQUEST_DATA = 'COMPLOGIN/REQUEST_DATA';export const COMP_LOGIN_RECEIVE_DATA = 'COMPLOGIN/RECEIVE_DATA';

index

import React from 'react';import Bundle from '../../../bundle/views/bundle';import * as actions from './actions';const view = (props) => {    return (        42c9814113858c7668de4a776bc31ec5 import("./lazy")}>
            {(View) => {                return 2fb732b7199e4f5e49a9d32783267755
            }}        2075647a73e9b735dd611345836fffdd
    );
};export {actions, view};

lazy 异步加载

  • 根据组件加载对应的 sagas\reducer\view

  • reducer 中的数据结构:[compLoginName]: compLoginReducer

import compLoginSagas from './sagas';import compLoginReducer from './reducer';import view from './views/Login';import {UumsCompsReducerNames} from '../../constants';const compLoginName = UumsCompsReducerNames.compLogin;const reducer = {
    [compLoginName]: compLoginReducer
};const sagas = {
    [compLoginName]: compLoginSagas
};export {sagas, reducer, view};

reducer

  • 纯函数

export default (state = {}, action) => {    const {type} = action;    switch (type) {        case types.COMP_LOGIN_REQUEST_DATA: {            return {                ...state, type: type, isFetching: true
            }
        }        case types.COMP_LOGIN_RECEIVE_DATA:            return {...state, type: type,isFetching: false, data: action.data};        default:            return {...state};
    }
}

sagas

异步调用

import * as http from '../axios/index';import {call, put, takeLatest} from 'redux-saga/effects';import {requestData, receiveData} from './actions';import {COMP_LOGIN_FIND_DATA} from './actionTypes';export const fetchData = ({funcName, params}) => {    return http[funcName](params).then(res => {        return res;
    });
};function* fetchLoginInfo(data) {    try {        let {stateName} = data;        yield put(requestData());        const result = yield call(fetchData, data);        yield put(receiveData(result, stateName));
    } catch (e) {        console.log(e);
    }
}function* sagas() {    yield takeLatest(COMP_LOGIN_FIND_DATA, fetchLoginInfo);
}export default sagas;

selector

记忆组件 selector

import {createSelector} from 'reselect';const getCompLoginData = (state) => state.compLoginData;export const 
selectVisibleMenuResourceTreeTable = createSelector(
    [getCompLoginData],
    (compLoginData) => compLoginData
);

本篇文章到这就结束了(想看更多就到PHP中文网React使用手册栏目中学习),有问题的可以在下方留言提问。

以上是React如何实现登录?react登录模块的详解的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn