同时多个axios请求_用 React+Antd 封装 Axios 实现全局 Loading 效果
生活随笔
收集整理的這篇文章主要介紹了
同时多个axios请求_用 React+Antd 封装 Axios 实现全局 Loading 效果
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
前言
今天在做 react 后臺管理的時候要實現一個全局 Loading 效果,通常使用 axios 庫與后端進行數據交互。為了更好的用戶體驗,在每次請求前添加一個加載效果,讓用戶知道在等待加載。
要實現這個功能,我們可以在每個組件請求手動添加加載效果返回后再將其隱藏,但如果每個請求都這么做,就要做多次重復設置顯得很麻煩,但好處是可以設置定制多種請求效果。但考慮到該項目場景為后臺管理系統,給管理員使用,花樣可以不用搞太多,統一優雅即可,故采取全局設置 loading 效果。
開發版本
"react":?"^16.13.1","antd":?"^4.0.4",
"axios":?"^0.19.2"
代碼說明
步驟
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("加載中..."?size="large"/>,?dom)
????}
????requestCount++
}
//?隱藏loadingfunction?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?=>?{
????//?判斷當前請求是否設置了不顯示Loadingif?(err.config.headers.isLoading?!==?false)?{
????????hideLoading()
????}return?Promise.reject(err)
})
//?返回后攔截
Axios.interceptors.response.use(res?=>?{
????//?判斷當前請求是否設置了不顯示Loadingif?(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?=?Axiosexport?default?Axios
??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;
}
//?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)
})
效果
?歡迎關注我掘金賬號和Github技術博客:
- 掘金:https://juejin.im/user/1257497033714477
- Github:https://github.com/Jacky-Summer
- 覺得對你有幫助或有啟發的話歡迎 star,你的鼓勵是我持續創作的動力~
- 如需在微信公眾號平臺轉載請聯系作者授權同意,其它途徑轉載請在文章開頭注明作者和文章出處。
總結
以上是生活随笔為你收集整理的同时多个axios请求_用 React+Antd 封装 Axios 实现全局 Loading 效果的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mybatis insert 重复数据2
- 下一篇: param注解报错_mybatis不加@