我们可以使用 axios 的 onDownloadProgress 来加载 API 吗?

Gui*_*ume 1 javascript api reactjs axios

我需要使用 axios 创建一个用于在反应项目中加载 API 的进度条,我发现了“onDownloadProgress”函数。但是我不知道我们是否可以使用它来获取诸如加载百分比之类的信息,还是仅用于文件下载?

所以我不确定我们是否可以通过此功能获取有关 API 加载的信息?

我试图在我的代码中实现这个功能:

componentWillMount() {
  axios.get('https://guillaumeduclos.fr/jd-portfolio/wp-json/wp/v2/posts')
  .then(response => {
    axios.onDownloadProgress = (progressEvent) => {
      let percentCompleted = Math.round( (progressEvent.loaded * 100) / progressEvent.total );
      console.log(percentCompleted);
    }
    this.setState({
      datas: response.data[0].acf.project_illustration.url,
      loading: false
    });
  })
  .catch(error => {
    if(error.response) {
      console.log(error.responderEnd);
    }
  });
Run Code Online (Sandbox Code Playgroud)

}

不显示 console.log()。感谢您的帮助。

V S*_*ren 7

您需要将onDownloadProgressin 作为选项传递。由于lengthComputable,它将打印出“Infinity”。

这是关于该问题的帖子:JQuery ajax progress via xhr

componentWillMount() {
axios.get('https://guillaumeduclos.fr/jd-portfolio/wp-json/wp/v2/posts', {
  onDownloadProgress: (progressEvent) => {
    let percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
    console.log(progressEvent.lengthComputable)
    console.log(percentCompleted);
  }
})
  .then((response) => {
    this.setState({
      datas: response.data[0].acf.project_illustration.url,
      loading: false
    })
  }).catch(error => {
    if (error.response) {
      console.log(error.responderEnd);
    }
  });
Run Code Online (Sandbox Code Playgroud)

}