preface

Today, the React backend management needs to implement a global Loading effect, usually using the AXIos library to interact with the backend data. For a better user experience, add a load effect before each request to let the user know they are waiting to load.

To do this, we could manually add loading effects to each component request and then hide them after they return, but if we did this for each request, it would be cumbersome to repeat the setup multiple times, but the benefit is that we can customize multiple request effects. However, considering that the project scene is a background management system for the administrator to use, there is no need to do too much variety, and it can be unified and elegant, so the loading effect of global setting is adopted.

Development version

"react": "^ 16.13.1"."antd": "^ 4.0.4." "."axios": "^ 0.19.2"
Copy the code

Code instructions

  1. The interface for request interception and response interception provided by AXIos controls how loading can be shown or hidden. Here I also set up no network and network timeout messages
  2. Spin component of ANTD is used to realize loading effect and message component is used to prompt message (ANTD. CSS is not introduced here because I set loading on demand)
  3. The variable requestCount is used as a counter to ensure that if there are multiple requests at the same time, the loading is not added at the same time, but only one, and the loading is not hidden until all requests are finished.
  4. By default, all requests will automatically have loading effect. If a request does not require the loading effect, you can set isLoading to false in the request headers.

steps

  1. Create a new file, axios.js, in the SRC directory
import axios from 'axios';
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { message, Spin } from 'antd'; Const Axios = axios.create({// baseURL: process.env.BASE_URL, // set the request baseURL timeout: 20000, / / set the timeout value}) / / set the post request head Axios. Defaults. Headers. Post ['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'// The number of requests currently being madeletRequestCount = 0 // Display loadingfunction showLoading () {
    if (requestCount === 0) {
        var dom = document.createElement('div')
        dom.setAttribute('id'.'loading')
        document.body.appendChild(dom)
        ReactDOM.render(<Spin tip="Loading..." size="large"/>, dom)} requestCount++} // hide loadingfunction hideLoading () {
    requestCount--
    if (requestCount === 0) {
        document.body.removeChild(document.getElementById('loading'))}} / / request before intercept Axios. Interceptors. Request. Use (config = > {/ / requestCount is 0, to create loading, avoid duplication of creationif(config.headers.isLoading ! = =false) {
        showLoading()
    }
    returnConfig}, err => {// Check whether Loading is not enabledif(err.config.headers.isLoading ! = =false) {
        hideLoading()
    }
    returnPromise. Reject (err)}) / / return after intercepting Axios. Interceptors. Response. Use (res = > {/ / whether the current request Loading is set upif(res.config.headers.isLoading ! = =false) {
        hideLoading()
    }
    return res
}, err => {
    if(err.config.headers.isLoading ! = =false) {
        hideLoading()
    }
    if (err.message === 'Network Error') {
        message.warning('Network connection is abnormal! ')}if (err.code === 'ECONNABORTED') {
        message.warning('Request timed out, please try again')}returnPromise.reject(err)}) // Introduce components and define them as prototype properties to make it easier to use Component.prototype.$axios = Axios

export default Axios

Copy the code
  1. Add loading styles to shared CSS files
#loading {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.75);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 9999;
    font-size: 20px;
}
Copy the code
  1. Axios request
// 1. Introduce a custom AXIos file path // 2. Use the React component to request a URLcomponentDidMount () {
    axios({
      url: '/manage/statistic/base_count.do'
    }).then(res => {
      this.setState(res.data)
    })
}
Copy the code

Without loading effect, write like this

axios({
  url: '/manage/statistic/base_count.do',
  headers: {
    'isLoading': false
  }
}).then(res => {
  this.setState(res.data)
})
Copy the code

The effect