今天在作react后台管理的时候要实现一个全局Loading效果,一般使用axios库与后端进行数据交互。为了更好的用户体验,在每次请求前添加一个加载效果,让用户知道在等待加载。css
要实现这个功能,咱们能够在每一个组件请求手动添加加载效果返回后再将其隐藏,但若是每一个请求都这么作,就要作屡次重复设置显得很麻烦,但好处是能够设置定制多种请求效果。但考虑到该项目场景为后台管理系统,给管理员使用,花样能够不用搞太多,统一优雅便可,故采起全局设置loading效果。react
"react": "^16.13.1", "antd": "^4.0.4", "axios": "^0.19.2"
1.在src目录下新建一个文件axios.jsios
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, // 设置请求的base url timeout: 20000, // 设置超时时长 }) // 设置post请求头 Axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8' // 当前正在请求的数量 let requestCount = 0 // 显示loading function showLoading () { if (requestCount === 0) { var dom = document.createElement('div') dom.setAttribute('id', 'loading') document.body.appendChild(dom) ReactDOM.render(<Spin tip="加载中..." size="large"/>, dom) } requestCount++ } // 隐藏loading function hideLoading () { requestCount-- if (requestCount === 0) { document.body.removeChild(document.getElementById('loading')) } } // 请求前拦截 Axios.interceptors.request.use(config => { // requestCount为0,才建立loading, 避免重复建立 if (config.headers.isLoading !== false) { showLoading() } return config }, err => { // 判断当前请求是否设置了不显示Loading if (err.config.headers.isLoading !== false) { hideLoading() } return Promise.reject(err) }) // 返回后拦截 Axios.interceptors.response.use(res => { // 判断当前请求是否设置了不显示Loading if (res.config.headers.isLoading !== false) { hideLoading() } return res }, err => { if (err.config.headers.isLoading !== false) { hideLoading() } if (err.message === 'Network Error') { message.warning('网络链接异常!') } if (err.code === 'ECONNABORTED') { message.warning('请求超时,请重试') } return Promise.reject(err) }) // 把组件引入,并定义成原型属性方便使用 Component.prototype.$axios = Axios export default Axios
2.添加loading样式在共用的css文件里axios
#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; }
3.axios请求后端
// 1. 引入自定义axios文件路径 // 2. 引入共用css文件(loading样式) // 3. 在react组件中正常写法请求url便可 componentDidMount () { axios({ url: '/manage/statistic/base_count.do' }).then(res => { this.setState(res.data) }) }
不加loading效果,这样写网络
axios({ url: '/manage/statistic/base_count.do', headers: { 'isLoading': false } }).then(res => { this.setState(res.data) })