如何在 axios 拦截器中为 React 项目添加全局加载/旋转效果 [英] How to add global loading/spin effect in axios interceptor for a React project

查看:53
本文介绍了如何在 axios 拦截器中为 React 项目添加全局加载/旋转效果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 React 项目中使用 axios 进行 API 调用,我想在我的 axios 拦截器中的 api 调用的请求和响应之间全局添加加载或旋转效果,这是我的拦截器的代码.

I am use axios for API call in a React project, and I want to add a loading or spinning effect globally in between a api call's request and response in my axios interceptor, here is the code of my interceptor.

import Axios from 'axios'

Axios.interceptors.request.use(function (config) {
  // spinning start to show
  const token = window.localStorage.token;
  if (token) {
     config.headers.Authorization = `token ${token}`
  }
  return config
}, function (error) {
  return Promise.reject(error);
});

Axios.interceptors.response.use(function (response) {
  // spinning hide
  return response;
}, function (error) {
  return Promise.reject(error);
});

推荐答案

也许您可以采用更简单的方法,在您的应用程序忙于通过 axios 加载数据时显示全屏加载消息?

Perhaps you could take a simpler approach, where you display a full-screen loading message while your app is busy loading data via axios?

例如,您可以在代码/项目中添加以下内容,以便在 axio 请求期间在屏幕上显示全局加载消息":

For example, you could make the following additions to your code/project to show a global "loading message" on screen while during axio requests:

CSS:

/* Define css class for global loading message to cover 
   screen during axios operations */

.loading-indicator:before {
    content: '';
    background: #000000cc;
    position: fixed;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    z-index: 1000;
}

.loading-indicator:after {
    content: 'Loading';
    position: fixed;
    width: 100%;
    top: 50%;
    left: 0;
    z-index: 1001;
    color:white;
    text-align:center;
    font-weight:bold;
    font-size:1.5rem;        
}

Javascript:

Javascript:

Axios.interceptors.request.use(function (config) {

  // spinning start to show
  // UPDATE: Add this code to show global loading indicator
  document.body.classList.add('loading-indicator');

  const token = window.localStorage.token;
  if (token) {
     config.headers.Authorization = `token ${token}`
  }
  return config
}, function (error) {
  return Promise.reject(error);
});

Axios.interceptors.response.use(function (response) {

  // spinning hide
  // UPDATE: Add this code to hide global loading indicator
  document.body.classList.remove('loading-indicator');

  return response;
}, function (error) {
  return Promise.reject(error);
});

使用这种方法,您甚至可以使用 CSS3 动画将正在加载"消息替换为动画微调器或类似的东西 - 希望这会有所帮助!

Using this method, you could even use CSS3 animations to replace the "loading" message with a animated spinner, or something similar - hope this helps!

这篇关于如何在 axios 拦截器中为 React 项目添加全局加载/旋转效果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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