如何在获取请求期间显示 Axios 的进度(不是下载或上传) [英] How to show progress of Axios during get request (not download or upload)

查看:145
本文介绍了如何在获取请求期间显示 Axios 的进度(不是下载或上传)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 Axios 收到我的请求时显示一个进度条.axios 包同时具有 onDownloadProgressonUploadProgress 以在下载或上传期间显示进度条,但在获取请求期间没有进度条.我搜索了很多问题和文章,但它们总是关于下载/上传进度或 Vue.js,我无法理解如何在 React 中进行.

我有以下代码下面(这将不起作用,因为我没有下载).

理想情况下,我会自己写;但我愿意考虑使用 axios-progress package 如果有人可以解释我我如何将 loadProgressBar() 与我的 Axios 请求集成.

I want is to show a progressbar while Axios is getting my requests. axios package has both onDownloadProgress and onUploadProgress to show a progressbar during download or upload, but no progress bar during get request. I've searched a lot of questions and articles but they are always about download/upload progress or for Vue.js and I fail to understand how to do it in React.

I have the following code down below (which will not work because I'm not downloading).

Ideally, I'd write it myself; but I'm willing to consider using axios-progress package if someone could explain me how I'd integrate the loadProgressBar() with my Axios request.

request = () => {
    this.setState({error: null, results: []})
    axios({
        method: 'get',
        url: process.env.REACT_APP_API_LOCALS,
        responseType: 'json',
        onDownloadProgress: (progressEvent) => {
            var percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
            this.setState({
                loading: percentCompleted
            })
        },
    })
    .then(
        (response) => {
            console.log(response)
            this.setState({
                results: response.data.results,
                error: null,
                totalPages: Math.ceil(response.data.count / response.data.results.length)
            })  
        }
    )
    .catch(
        (error) => {
            this.setState({
                loading: null,
                error: true
            })  
        }
    );
}

推荐答案

以下是我在 React 中有用的内容:

Here's what worked for me in React:

const client = axios.create({
  baseURL: 'http://localhost:10000/v1/client',
  timeout: 20000
})

let result = await client.get('/fetchMeSomething', {
  onDownloadProgress: progressEvent => {
    const total = parseFloat(progressEvent.currentTarget.responseHeaders['Content-Length'])
    const current = progressEvent.currentTarget.response.length

    let percentCompleted = Math.floor(current / total * 100)
    console.log('completed: ', percentCompleted)
  }
})
.then(res => {
  console.log("All DONE: ", res.headers)
  return res.data
})

这篇关于如何在获取请求期间显示 Axios 的进度(不是下载或上传)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆