


How to implement login in React? Detailed explanation of react login module
Sep 11, 2018 pm 04:29 PMThis article mainly introduces the login module of react, and introduces the login situation of react in detail. Now let us take a look at the text of the article
React-based login
The first login
Login page submission login handleSubmit(), medium Make API requests directly. After successful login request, jump to history.push(nextPathname, null);
For the implementation method, please refer to http://blog.csdn.net/qq_27384769/article/details/78775835
Second login
After the Login page submits login handleSubmit(), an asynchronous request is initiated through saga.
After the request is successful, initiate an action and call the reducer. Reload the Login page.
In the Login page life cycle componentWillReceiveProps verifies the login information request to jump.
The following is an explanation of the second login method
reducer Data structure in
auth:{ type:?"COMPLOGIN/RECEIVE_DATA",? isFetching:?false,? data:?{uid:?1,?permissions:?Array(5),?role:?"系統(tǒng)管理員",?roleType:?1,?userName:?"系統(tǒng)管理員"} }
Code
login.jsx
componentWillReceiveProps login Adjust after success
handleSubmit handles submission login
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?(????????????<p className="login"> ????????????????<p className="login-form"> ????????????????????<p className="login-logo"> ????????????????????????<span>React?Admin</span> ????????????????????</p> ????????????????????<Form onSubmit={this.handleSubmit} style={{maxWidth: '300px'}}> ????????????????????????<FormItem> ????????????????????????????{getFieldDecorator('userName',?{ ????????????????????????????????rules:?[{required:?true,?message:?'請輸入用戶名!'}], ????????????????????????????})(????????????????????????????????<Input prefix={<Icon type="user" style={{fontSize: 13}}/>} ???????????????????????????????????????placeholder="管理員輸入admin,?游客輸入guest"/> ????????????????????????????)}????????????????????????</FormItem> ????????????????????????<FormItem> ????????????????????????????{getFieldDecorator('password',?{ ????????????????????????????????rules:?[{required:?true,?message:?'請輸入密碼!'}], ????????????????????????????})(????????????????????????????????<Input prefix={<Icon type="lock" style={{fontSize: 13}}/>}?type="password" ???????????????????????????????????????placeholder="管理員輸入admin,?游客輸入guest"/> ????????????????????????????)}????????????????????????</FormItem> ????????????????????????<FormItem> ????????????????????????????{getFieldDecorator('remember',?{ ????????????????????????????????valuePropName:?'checked', ????????????????????????????????initialValue:?true, ????????????????????????????})(????????????????????????????????<Checkbox>記住我</Checkbox> ????????????????????????????)}????????????????????????????<a className="login-form-forgot" href="" style={{float: 'right'}}>忘記密碼</a> ????????????????????????????<Button type="primary" htmlType="submit" className="login-form-button" style={{width: '100%'}}> ????????????????????????????????登錄????????????????????????????</Button> ????????????????????????????或?<a href="">現(xiàn)在就去注冊!</a> ????????????????????????????<p> ????????????????????????????????<Icon type="github" onClick={this.gitHub}/>(第三方登錄)????????????????????????????</p> ????????????????????????</FormItem> ????????????????????</Form> ????????????????</p> ????????????</p> ????????); ????} }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 Click the button to initiate a request
requestData Before calling the API
requestData Call the API to obtain To data
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?(????????<Bundle load={() =>?import("./lazy")}> ????????????{(View)?=>?{????????????????return?<View {...props}/> ????????????}}????????</Bundle> ????); };export?{actions,?view};
lazy Asynchronous loading
#Load the data structure in the corresponding sagas\reducer\view
#reducer according to the component: [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
Pure function
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
Asynchronous call
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
Memory component selector
import {createSelector} from 'reselect';const getCompLoginData = (state) => state.compLoginData;export const selectVisibleMenuResourceTreeTable = createSelector( [getCompLoginData], (compLoginData) => compLoginData );
This article ends here (if you want to see more, go to the PHP Chinese websiteReact User Manual column), if you have any questions, you can leave a message below.
The above is the detailed content of How to implement login in React? Detailed explanation of react login module. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

ReactRouter User Guide: How to Implement Front-End Routing Control With the popularity of single-page applications, front-end routing has become an important part that cannot be ignored. As the most popular routing library in the React ecosystem, ReactRouter provides rich functions and easy-to-use APIs, making the implementation of front-end routing very simple and flexible. This article will introduce how to use ReactRouter and provide some specific code examples. To install ReactRouter first, we need

PHP, Vue and React: How to choose the most suitable front-end framework? With the continuous development of Internet technology, front-end frameworks play a vital role in Web development. PHP, Vue and React are three representative front-end frameworks, each with its own unique characteristics and advantages. When choosing which front-end framework to use, developers need to make an informed decision based on project needs, team skills, and personal preferences. This article will compare the characteristics and uses of the three front-end frameworks PHP, Vue and React.

Integration of Java framework and React framework: Steps: Set up the back-end Java framework. Create project structure. Configure build tools. Create React applications. Write REST API endpoints. Configure the communication mechanism. Practical case (SpringBoot+React): Java code: Define RESTfulAPI controller. React code: Get and display the data returned by the API.

Vue.js is suitable for small and medium-sized projects and fast iterations, while React is suitable for large and complex applications. 1) Vue.js is easy to use and is suitable for situations where the team is insufficient or the project scale is small. 2) React has a richer ecosystem and is suitable for projects with high performance and complex functional needs.

Netflixusesacustomframeworkcalled"Gibbon"builtonReact,notReactorVuedirectly.1)TeamExperience:Choosebasedonfamiliarity.2)ProjectComplexity:Vueforsimplerprojects,Reactforcomplexones.3)CustomizationNeeds:Reactoffersmoreflexibility.4)Ecosystema

React combines JSX and HTML to improve user experience. 1) JSX embeds HTML to make development more intuitive. 2) The virtual DOM mechanism optimizes performance and reduces DOM operations. 3) Component-based management UI to improve maintainability. 4) State management and event processing enhance interactivity.

The React ecosystem includes state management libraries (such as Redux), routing libraries (such as ReactRouter), UI component libraries (such as Material-UI), testing tools (such as Jest), and building tools (such as Webpack). These tools work together to help developers develop and maintain applications efficiently, improve code quality and development efficiency.

Netflix uses React as its front-end framework. 1) React's componentized development model and strong ecosystem are the main reasons why Netflix chose it. 2) Through componentization, Netflix splits complex interfaces into manageable chunks such as video players, recommendation lists and user comments. 3) React's virtual DOM and component life cycle optimizes rendering efficiency and user interaction management.
