Explain in detail the login function of React combined with Form component of Antd

  • 2021-11-01 23:21:51
  • OfStack

Directory 1. React combined with Antd to realize login function
2. React combined with Antd to realize login function

1. React combined with Antd to realize login function

Introduce the required Antd component with the following code:


import { Form, Icon, Input, Button, message } from 'antd'

In Login. jsx, create an Login component. When exposing components, you need to use Form components for packaging, and packaging Form components generates a new component Form (Login). At the same time, the new component will pass a powerful object attribute form to Form components, so that you can get the value of Form form, which is also the embodiment of high-order components and high-order functions. The code is as follows:


class Login extends Component {}
const WrapLogin = Form.create()(Login)
export default WrapLogin

When rendering the form inside render, you can get form form through this. props first, and get getFieldDecorator in form for bidirectional binding with the form. In getFieldDecorator, item 1 is the value value corresponding to the form item, item 2 is the configuration object, and the property name is a specific number of names. For example, rules is a verification rule. In rules, you can set required as required, message as verification copy, pattern as regular expression verification, max as maximum length and min as minimum length. Another example is that initialValue is the initial value of the form item. For rules verification, you can use declarative verification, that is, you can directly use verification rules defined by others, and you can also customize validator, function (rule, value, callback). You must have callback callback function, and the code is as follows:


class Login extends Component {
 validPwd = (rule, value, callback) => {
  if (!value) {
   callback(' Password must be entered ')
  } else if (value.length < 4) {
   callback(' Password length cannot be less than 4 Bit ')
  } else if (value.length > 12) {
   callback(' Password length cannot be greater than 12 Bit ')
  } else if (!/^[a-zA-Z0-9_]+$/.test(value)) {
   callback(' Password must be in English, numeric or underlined ')
  } else {
   callback()
  }
 }

 render () {
  const form = this.props.form
  const { getFieldDecorator } = form

  return (
   <div className="login">
    <header className="login-header">
     <img src={logo} alt="logo"></img>
     <h1>React  Background management system </h1>
    </header>
    <section className="login-content">
     <h2> User login </h2>
     <Form>
      <Form.Item>
       {
        getFieldDecorator('username', { 
         rules: [
          { required: true, whitespace: true, message: ' User name must be entered '},
          { min: 4, message: ' The user name is at least 4 Bit '},
          { max: 12, message: ' The user name is at least 12 Bit '},
          { pattern: /^[a-zA-Z0-9_]+$/, message: ' User name must be English, numeric or underlined '}
         ],
         // initialValue: 'admin', 
        })(
         <Input
          prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />}
          placeholder=" User name "
         />
        )
       }
      </Form.Item>
      <Form.Item>
       {
        getFieldDecorator('password', {
         rules: [
          { validator: this.validPwd }
         ]
        })(
         <Input
          prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />}
          type="password"
          placeholder=" Password "
         />
        )
       }
      </Form.Item>
      <Form.Item>
       <Button type="primary" htmlType="submit" className="login-form-button">
          Landing 
       </Button>
      </Form.Item>
     </Form>
    </section>
   </div>
  )
 }
}

const WrapLogin = Form.create()(Login)
export default WrapLogin

We can define two tool classes to operate the login object. memoryUtils is a tool module for saving some data in memory, and storageUtils is a tool module for managing local data storage, as follows:

memoryUtils. js with the following code:


export default {
 user: {},
 product: {}
}

storageUtils. js with the following code:


import store from 'store'

const USER_KEY = 'user_key'

export default {
 //  Save  user
 saveUser (user) {
  store.set(USER_KEY, user)
 },

 //  Read  user
 getUser () {
  return store.get(USER_KEY) || {}
 },

 //  Delete  user
 removeUser () {
  store.remove(USER_KEY)
 }
}

Define the login interface request function, which can be encapsulated by axios first, and get response. data as follows:

ajax. js with the following code:


import axios from 'axios'
import {message} from 'antd'

export default function ajax(url, data={}, type='GET') {

 return new Promise((resolve, reject) => {
  let promise
  if(type==='GET') { 
   promise = axios.get(url, {
    params: data 
   })
  } else { 
   promise = axios.post(url, data)
  }
  promise.then(response => {
   resolve(response.data)
  }).catch(error => {
   message.error(' Error in request : ' + error.message)
  })
 })

}

index. js with the following code:


import jsonp from 'jsonp'
import ajax from './ajax'
import { message } from 'antd'

const BASE = ''

export const reqLogin = (username, password) => ajax(BASE + '/login', { username, password}, 'POST')

export const reqCategories = (parentId) => ajax(BASE + '/manage/category/list', {parentId})

export const reqAddCategories = ({parentId, categoryName}) => ajax(BASE + '/manage/category/add', {parentId, categoryName}, 'POST')

export const reqUpdateCategories = ({categoryId, categoryName}) => ajax(BASE + '/manage/category/update', {categoryId, categoryName}, 'POST')

export const reqCategory = (categoryId) => ajax(BASE + '/manage/category/info', { categoryId })

export const reqProducts = ({pageNum, pageSize}) => ajax(BASE + '/manage/product/list', { pageNum, pageSize})

export const reqUpdateStatus = ({productId, status}) => ajax(BASE + '/manage/product/updateStatus', {productId, status}, 'POST')

export const reqSearchProducts = ({ pageNum, pageSize, searchName, searchType}) => ajax(BASE + '/manage/product/search', {
 pageNum,
 pageSize,
 [searchType]: searchName
})

export const reqDeleteImg = (name) => ajax(BASE + '/manage/img/delete', {name}, 'POST')

export const reqAddUpdateProduct = (product) => ajax(BASE + '/manage/product/' + (product._id ? 'update' : 'add'), product, 'POST')

export const reqRoles = () => ajax(BASE + '/manage/role/list')

export const reqAddRole = (roleName) => ajax(BASE + '/manage/role/add', {roleName}, 'POST')

export const reqUpdateRole = (role) => ajax(BASE + '/manage/role/update', role, 'POST')

export const reqUsers = () => ajax(BASE + '/manage/user/list')

export const reqDeleteUser = (userId) => ajax(BASE + '/manage/user/delete', {userId}, 'POST')

export const reqAddOrUpdateUser = (user) => ajax(BASE + '/manage/user/'+(user._id ? 'update': 'add'), user, 'POST')

export const reqWeather = (city) => {

 return new Promise((resolve, reject) => {
  const url = `http://api.map.baidu.com/telematics/v3/weather?location=${city}&output=json&ak=IOXimfoqOUVq2KcYCiQU9cMF7hyN5kFB`
  jsonp(url, {}, (err, data) => {
   console.log('jsonp()', err, data)
   if (!err && data.status==='success') {
    const {dayPictureUrl, weather} = data.results[0].weather_data[0]
    resolve({dayPictureUrl, weather})
   } else {
    message.error(' Failed to get weather information !')
   }

  })
 })
}

These tool classes and interfaces are introduced with the following code:


import { reqLogin } from '../../api'
import memoryUtils from '../../utils/memoryUtils'
import storageUtils from '../../utils/storageUtils'

Bind the Form form to the onSubmit event, handleSubmit. In this event, you first use event. preventDefault () to block the default behavior of the event. If you want to get input data for a form item, you can use form. getFieldsValue (). However, you need to pre-validate the form data before submitting it, using this. props. form. validateFields, which can get the values of all the form fields and determine whether the form data is wrong. If yes, the pre-check is passed, the values of username and password are obtained from values, and then the login request is initiated through reqLogin interface combined with async and await. If the response status code is correct, login is successful. Save user, save it in memory and locally, and then jump to the main management interface using this. props. history. replace. Otherwise, login fails. In render, if the user has logged in, you need to use Redirect to automatically jump to the main management interface. The code is as follows:


 handleSubmit = (event) => {
  event.preventDefault()

  this.props.form.validateFields(async (err, values) => {
   if (!err) {
    const { username, password } = values
    const result = await reqLogin(username, password)
    if (result.status === 0) { 
     message.success(' Login Successful ')
     const user = result.data
     memoryUtils.user = user
     storageUtils.saveUser(user)
     this.props.history.replace('/')
    } else { 
     message.error(result.msg)
    }
   } else {
    console.log(err)
   }
  })

2. React combined with Antd to realize login function

React is combined with Antd to realize the login function. The complete code is as follows:
login. jsx with the following code:


import React, { Component } from 'react'
import { Form, Icon, Input, Button, message } from 'antd'
import { Redirect } from 'react-router-dom'
import './login.less'
import logo from '../../assets/images/logo.png'
import { reqLogin } from '../../api'
import memoryUtils from '../../utils/memoryUtils'
import storageUtils from '../../utils/storageUtils'

class Login extends Component {

 handleSubmit = (event) => {
  event.preventDefault()

  this.props.form.validateFields(async (err, values) => {
   if (!err) {
    const { username, password } = values
    const result = await reqLogin(username, password)
    if (result.status === 0) { 
     message.success(' Login Successful ')
     const user = result.data
     memoryUtils.user = user
     storageUtils.saveUser(user)

     this.props.history.replace('/')
    } else { 
     message.error(result.msg)
    }
   } else {
    console.log(err)
   }
  })

 }

 validPwd = (rule, value, callback) => {
  if (!value) {
   callback(' Password must be entered ')
  } else if (value.length < 4) {
   callback(' Password length cannot be less than 4 Bit ')
  } else if (value.length > 12) {
   callback(' Password length cannot be greater than 12 Bit ')
  } else if (!/^[a-zA-Z0-9_]+$/.test(value)) {
   callback(' Password must be in English, numeric or underlined ')
  } else {
   callback()
  }
 }


 render () {

  const user = memoryUtils.user
  if (user && user._id) {
   return <Redirect to="/"></Redirect>
  }

  const form = this.props.form
  const { getFieldDecorator } = form

  return (
   <div className="login">
    <header className="login-header">
     <img src={logo} alt="logo"></img>
     <h1>React  Background management system </h1>
    </header>
    <section className="login-content">
     <h2> User login </h2>
     <Form onSubmit={this.handleSubmit}>
      <Form.Item>
       {
        getFieldDecorator('username', { 
         rules: [
          { required: true, whitespace: true, message: ' User name must be entered '},
          { min: 4, message: ' The user name is at least 4 Bit '},
          { max: 12, message: ' The user name is at least 12 Bit '},
          { pattern: /^[a-zA-Z0-9_]+$/, message: ' User name must be English, numeric or underlined '}
         ],
         // initialValue: 'admin',
        })(
         <Input
          prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />}
          placeholder=" User name "
         />
        )
       }
      </Form.Item>
      <Form.Item>
       {
        getFieldDecorator('password', {
         rules: [
          { validator: this.validPwd }
         ]
        })(
         <Input
          prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />}
          type="password"
          placeholder=" Password "
         />
        )
       }
      </Form.Item>
      <Form.Item>
       <Button type="primary" htmlType="submit" className="login-form-button">
          Landing 
       </Button>
      </Form.Item>
     </Form>
    </section>
   </div>
  )
 }
}

const WrapLogin = Form.create()(Login)
export default WrapLogin

login. less with the following code:


class Login extends Component {}
const WrapLogin = Form.create()(Login)
export default WrapLogin
0

Related articles: