首页 > 解决方案 > 使用 Axios 和 React 显示加载微调器(可能是 Redux)

问题描述

我的目标是在调用 http 请求时显示加载微调器。我想在全局范围内执行此操作,这意味着,当任何组件调用某个 api 时,会自动显示微调器,最好没有额外的代码来控制微调器。

我正在使用反应和 axios。我知道 axios 的拦截器。

我的实际结构:

<Component App>
    <Component A />
    <Component B />
    <Loading Component>
</Component App>

我不知道是否有可能做出反应,但我尝试制作一个通用类来实现有关服务的基本信息,例如 baseUrl 和 http 拦截器。因此,当需要调用 API 服务时,我使用通用类创建一个专门的类,并将该概念中的所有 api 方法集中在那里,然后使用基类调用 axios 方法 get、post 等。因此,拦截器出现并在请求之前显示微调器并在请求之后隐藏。

这个想法是一个组件调用专用类来调用 API 并显示微调器,直到请求运行。

我想用redux来使状态是全局的,但我不知道是否可以在一个类中实现(API Class Base和Specialized API Class)

我的问题: - 是否可以使用这种架构?- 如果是,如何实现和使用 redux?- 使用类的权利还是更好地使用组件来实现基本服务类和专用类?

应用组件:

class App extends Component {

  constructor(props) {
      super(props);

      this.state = {
          rows: []
      };
  }

  componentDidMount() {
var service = new specializedService();

     var response = 

 specializedService.someAPIMethod(1).then((res) => {
           this.setState({
               rows: res.data
           });
     });
}

render() {
return (
        <div className="App">
                <Component A rows={this.state.rows} />
                <Component B rows={this.state.rows}/>
                <Loading />
        </div>
    );
  }

专业服务:

import serviceBase from "./serviceBase";

class specializedService {

    someAPIMethod(id) {
        return serviceBase.get('someMethod/' + id);
    };

}

服务基础:

import axios from "axios";

const serviceBase = () => {

    const api = axios.create({
        baseURL: 'https://xxxxx.xxxxx.com/xxxxxx/'
    });

    api.interceptors.request.use(async (config) => {
        try{
            // In this moment, show the spinner
            // showLoading();
        }
        catch(e)
        {
            alert('Error request' + e);
        }

        return config;
    });

    api.interceptors.response.use(async (config) => {
        try {
            // In this moment, hide the spinner
            // hideLoading();
        }
        catch(e)
        {
            alert('Error response' + e);   
        }

        return config;
    });

    return api;
};

export default serviceBase;

我做了一个简单的例子来说明情况,但是我没有连接redux https://repl.it/@DiegoFerreira1/LoadingSpinnerApp

标签: reactjsreduxreact-reduxaxios

解决方案


这使用 redux 和 thunk 非常方便。

但是,你可以使用类似的黑客,

this.state = {
 rows: [],
 isLoading: false,
}

apiCallFunction = () => {

 this.setState(prevState => ({ isLoading: !prevState.isLoading }) // to be true..

 // api call..
 // upon response success => 
 this.setState(prevState => ({
   isLoading: !prevState.isLoading, // to be false..
   rows: prevState.rows = response json,
 })
}

在渲染中,

render () {
 return (
  {isLoading && <Spinner />}
  {... handle the rest} 
 )
}

推荐阅读