How to implement login and registration in react

藏色散人
Release: 2023-01-05 09:55:36
Original
2194 people have browsed it

React method to implement login and registration: 1. Build style components; 2. Create basic routing components for the login registration page, code such as "import React,{Component} from 'react'; import{PhoneLogin}from '... {render(){...}"; 3. Display the login registration route; 4. Connect to the database to implement the login registration code; 5. Determine whether the user has logged in by judging local storage, and click to judge when logging in. Can.

How to implement login and registration in react

The operating environment of this tutorial: Windows 10 system, react18.0.0 version, Dell G3 computer.

How to implement login and registration in react?

react simply implements login registration logic (localStorage simulation implementation, database connection and implementation by querying the database)

1. Build style components

import styled from 'styled-components';export const MineContainer = styled.div`
   flex:1;
`export const PhoneLogin =styled.div`
   padding:10px;
   input{
      margin:3px;
   }

`export const UserRegister = styled.div`
   padding:10px;
   input{
      margin:3px;
   }
`
Copy after login

localStorage simulation implementation

2. Basic routing components for login and registration pages

import React ,{Component} from 'react';import {PhoneLogin} from './MineStyleComponent'class Login extends Component {
   render(){
      return(
         <phonelogin>
            手机号:<input><br>
            验证码:<input><br>
            <button>登录</button>
         </phonelogin>
      )
   }}export default Login;==========================================================================================import React ,{Component} from 'react';import {UserRegister} from './MineStyleComponent'class Register extends Component {
   render(){
      return(
         <userregister>
            手机号:<input><br>
            密码:<input><br>
            验证码:<input><br>
            <button>登录</button>
         </userregister>
      )
   }}export default Register;
Copy after login

3. Display of login and registration routes

import React, { Component} from 'react';import {MineContainer} from './MineStyleComponent'import Login from './Login';import Register from './register';import {Route} from 'react-router-dom'class Mine extends Component {

   constructor(){
      super()
      this.state={
         loginFlag:false,//通过开关切换登录方式
      }
   }

   check = ()=>{//通过编程导航进行两个路由的切换

      if(this.state.loginFlag){
         this.props.history.push('/mine/register')
      }else{
         this.props.history.push('/mine/login')
      }

      this.setState({
         loginFlag:!this.state.loginFlag,
      })

   }
   
   render(){
      const {loginFlag} = this.state      return (
         <minecontainer>
           <route></route>
           <route></route>
           <button> { loginFlag?'用户名登录':'短信验证登录'} </button>
         </minecontainer>
      )
   }}export default Mine;
Copy after login

How to implement login and registration in react

4. Simple access using local data Implement the logical process.

How to store one user locally

import React ,{Component} from 'react';import {UserRegister} from './MineStyleComponent'class Register extends Component {

   //本地存储一个账户的模拟登录注册写法
   //逻辑:通过判断本地存储,来确定用户是否登录过,点击登陆时进行判断

   LoginClick = () =>{

      const username = this.users.value;
      const password = this.password.value;
      let  ls_users = localStorage.getItem('users');

      if(ls_users){
         //如果ls_users存在证明已有用户注册,判断密码,用户名是否正确
         ls_users = JSON.parse(ls_users)
         
         if(ls_users.username===username&&ls_users.password===password){
            alert('登录成功')
            this.props.history.push('/home')
         }else{
            alert('用户名或登录密码输入错误')
         }

      }else{
         //没有用户注册,直接保存到本地存储
         localStorage.setItem('users',JSON.stringify({username,password}))
         this.props.history.push('/home')
      }
   }


   render(){
      return(
         <userregister>
            用户名:<input>this.users=el} /><br>
            密码:<input>this.password=el} /><br>
            验证码:<input><br>
            <button> 登录</button>
         </userregister>
      )
   }}export default Register;
Copy after login

How to store multiple users in localStorage

import React ,{Component} from 'react';import {UserRegister} from './MineStyleComponent'class Register extends Component {

   //本地存储一个账户的模拟登录注册写法
   //逻辑:通过判断本地存储,来确定用户是否登录过,点击登陆时进行判断

   LoginClick = () =>{
      let obj = [];
      const username = this.users.value;
      const password = this.password.value;
      let  ls_users = localStorage.getItem('users');

      if(ls_users){
         //如果ls_users存在证明已有至少用户注册,
         obj = JSON.parse(ls_users)
         console.log(obj)
         
         //对本地存储数据进行便利与输入值对比
         let fg = obj.some (item => {
            if(item.username===username) return true//用户名已存在
         })

         if(fg){//fg为真找到用户名,接下里对密码判断
            //对存储数据遍历,比对用户名名与密码
            let f=false
            obj.map(item => {
               if(item.username===username&&item.password===password){
                  f=true; 
                  return f;
               }     
            })
            if(f){//查询正确可以正常登录
               alert('登录成功')
               this.props.history.push('/home')
            }else{
               alert('密码错误')
            }

         }else{//没找到对将用户保存到本地,进行自动注册
            obj.push({username,password});
            localStorage.setItem('users',JSON.stringify(obj))
            this.props.history.push('/home')
         }
        
      }else{
         //没有用户注册,直接保存到本地存储
         obj.push({username,password})
         localStorage.setItem('users',JSON.stringify(obj))
         this.props.history.push('/home')
      }
   }


   render(){
      return(
         <userregister>
            用户名:<input>this.users=el} /><br>
            密码:<input>this.password=el} /><br>
            验证码:<input><br>
            <button> 登录</button>
         </userregister>
      )
   }}export default Register;
Copy after login

Connect to the database to implement login registration code

1. Database operation code
const { userSchema } = require('./schema');const { userModel } = require ('./module');//连接数据库const connect = require ('./connect');connect.init();//数据库操作const db = {
   user: {
      add(data){//数据添加
         const user = new userModel(data)
         user.save()
      },

      query(){//数据库查询,通过promise异步函数将结果返回出去
         return new Promise( (resolve,reject)=>{
            userModel.find( {},(err,docs) => {//查询数据库所有
               if(err) console.log(err) 
               resolve(docs)//将查询结果返回出去
            })
         })
      }

   }}module.exports = {
   user: db.user}
Copy after login
2. Server routing code (server built by express in Nodejs)
//打造用户信息接口const express = require ('express');const router = express.Router();const {user} = require ('../db');//打造restful接口,不同接口暴露不同功能人router.route('/userInfo')
 
   .post( async (req,res,next) => {
          
      const { userName, pass} = req.body      const result = await user.query()

      //判断请求与数据库数据,在遍历前需要判断后台查询是否为空值
      var f =result && result.some( item => {
         if( item.userName === userName ) return true
      })

      if(f){//证明用户名存在,需要判断密码是否正确
            let passFlag = result&&result.some( (item) => {
               if(item.userName===userName&&item.pass===pass){
                  return true
               }
         });

         if(passFlag){//密码正确,登录成功
               res.render('user',{     
                  data:JSON.stringify({
                     info:'登录成功',
                     status:2
                  })
               })
         }else{//密码错误
               res.render('user',{     
                  data:JSON.stringify({
                     info:'用户名已存在或用户密码错误',
                     status:0
                  })
               })
         }


      }else{//用户不存在,直接存入数据库,注册
         user.add({...req.body})
         res.render('user',{     
            data:JSON.stringify({
               info:'注册成功',
               status:1
            })
         })
      }  
   });module.exports = router//暴露路由接口
Copy after login

3 , The front page displays the operation code

import React ,{Component} from 'react';import {UserRegister} from './MineStyleComponent';import http from '../../utils/http';class Register extends Component {

   //本地存储一个账户的模拟登录注册写法
   //逻辑:通过判断本地存储,来确定用户是否登录过,点击登陆时进行判断

  async LoginClick (){
      const username = this.users.value;
      const password = this.password.value;
      
      const params = new URLSearchParams()
      params.append('userName',username);
      params.append('pass',password)

      const res = await http({//调用封装好的axios数据请求方法
         url:'http://localhost:3000/userInfo',
         method:'POST',
         data:params      })
      if( res.data.status === 0 ){
         alert('用户名已经存在或是用户名密码错误')
       }else if ( res.data.status === 1){
         alert('注册成功')
       }else {
         this.props.history.push('/home')
         alert('登录成功')
       }

   }

   render(){
      return(
         <userregister>
            用户名:<input>this.users=el} /><br>
            密码:<input>this.password=el} /><br>
            验证码:<input><br>
            <button> 登录</button>
         </userregister>
      )
   }}export default Register;
Copy after login
Recommended learning: "react video tutorial"

The above is the detailed content of How to implement login and registration in react. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template