最近在做一個后台管理系統供內部人員使用,交互性沒有那么強,所以對於每個頁面請求時要加loading,感覺要寫的比較麻煩,然后去百度了下能不能全局實現loading:
需要loading的請求發出后,讓loading顯示,請求后無論成功還是失敗就讓loading關閉
大概代碼如下:
const { request } = require("http") // 當前正在請求的數量 let requestCount = 0 // 顯示loading const showLoading = () => { if (requestCount === 0) { // 解決一個頁面多個接口請求需要loading const dom = document.createElement('div') dom.setAttribute('id', 'loading') document.body.appendChild(dom) ReactDOM.render(<Spin tip="加載中" size="large" />, dom) } requestCount ++ } // 隱藏loading const hideLoading = () => { requestCount -- if (requestCount === 0) { document.body.removeChild(document.getElementById('loading')) } } // eg: if (options?.headers?.isLoading) { showLoading() } fetch().then(() => { if (options?.headers?.isLoading) { hideLoading() } // DO SOME }).catch(() => { if (options?.headers?.isLoading) { hideLoading() } }) // 外部調用 request(url, { headers: { isLoading: true } })