React + AntdMobile + Axios 實現全局Loading提示組件


1.問題:

  開發項目時需要在接口等待期間調用一個Loading組件提示組件提示用戶操作已經受理;

  最初的解決方案是在每一個調用了接口的頁面直接使用 AntdMobile 的活動指示器組件 <ActivityIndicator />,后續開發中發現該方案代碼冗余度太高並且屬於重復工作,查閱資料后決定在axios攔截器中進行一些處理以實現全局Loading提示組件;

2.解決方案:

  使用 ReactDOM、AntdMobile 配合 Axios攔截器 實現一個全局Loading組件,調用接口時自動展示Loading;

  React:ReactDOM.render();

  AntdMobile:<ActivityIndicator />;https://mobile.ant.design/components/activity-indicator-cn/

  axios:interceptors;http://www.axios-js.com/zh-cn/docs/#%E6%8B%A6%E6%88%AA%E5%99%A8

配置axios

axios.js 

 

 1 import React from 'react'
 2 import { render } from 'react-dom'
 3 import axios from 'axios'
 4 import { ActivityIndicator, Toast } from 'antd-mobile'
 5 import history from '@/utils/history'
 6 
 7 var CancelToken = axios.CancelToken
 8 var source = CancelToken.source()
 9 let httpRequestCount = 0
10 
11 const showLoading = () => {
12   if (httpRequestCount === 0) {
13     const loadingContainer = document.createElement('div')
14     loadingContainer.setAttribute('id', 'axiosLoading')
15     document.body.appendChild(loadingContainer)
16     render(<ActivityIndicator toast text='Loading...' animating />, loadingContainer)
17   }
18   httpRequestCount++
19 }
20 const hideLoading = () => {
21   httpRequestCount--
22   if (httpRequestCount === 0) {
23     document.querySelector('body').removeChild(document.querySelector('#axiosLoading'))
24   }
25 }
26 
27 axios.source = source
28 
29 axios.interceptors.request.use(function (config) {
30   showLoading()
31   return config
32 }, handleError)
33 
34 axios.interceptors.response.use(function responseInterceptor (response) {
35   hideLoading()
36   // Do something with response data
37   if (response && response.status === 200 && response.data) {
38     return handleRes(response.data)
39   }
40   if (response && response.status === 999 && response.data) {
41     return handleRes(response.data)
42   }
43   return Promise.reject(response.data && response.data.responseMessage)
44 }, handleError)
45 
46 function handleError (error) {
47   hideLoading()
48   history.push('/')
49   return Promise.reject(error)
50 }
51 
52 function handleRes (data) {
53   return new Promise((resolve, reject) => {
54     if (data && data.resultCode) {
55       switch (data.resultCode) {
56         case '0':
57           return resolve(data)
58         default:
59           Toast.fail(data.resultDesc)
60           return resolve(data)
61       }
62     } else {
63       return resolve(data)
64     }
65   })
66 }
67 
68 // ...

 

 

 

完成 axios的配置后在使用axios調用接口的等待期間則會吹出現提示信息和動畫;

若是需要在某些接口等待期間不進行提示可以在接口調用時增加配置項然后在axios攔截器中進行處理;

參考網址:https://segmentfault.com/a/1190000022195227


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM