1.問題:react
開發項目時須要在接口等待期間調用一個Loading組件提示組件提示用戶操做已經受理;ios
最初的解決方案是在每個調用了接口的頁面直接使用 AntdMobile 的活動指示器組件 <ActivityIndicator />,後續開發中發現該方案代碼冗餘度過高而且屬於重複工做,查閱資料後決定在axios攔截器中進行一些處理以實現全局Loading提示組件;axios
2.解決方案:segmentfault
使用 ReactDOM、AntdMobile 配合 Axios攔截器 實現一個全局Loading組件,調用接口時自動展現Loading;antd
React:ReactDOM.render();app
AntdMobile:<ActivityIndicator />;https://mobile.ant.design/components/activity-indicator-cn/dom
axios:interceptors;http://www.axios-js.com/zh-cn/docs/#%E6%8B%A6%E6%88%AA%E5%99%A8ide
配置axios動畫
axios.js spa
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攔截器中進行處理;