React Hooks:使用axios拦截器显示全局微调器吗?

时间:2019-12-14 14:19:50

标签: reactjs axios react-hooks interceptor react-context

我想添加一个在 React 中进行API调用时要呈现的Loader组件。我想使用反应上下文+钩子代替redux

正如反应挂钩的规则所述,我们不应在反应组件之外使用反应挂钩。但是我需要在 Axios 拦截器内分派SHOW_LOADERHIDE_LOADER,如下所示。

有没有办法做到这一点?

import axios from "axios";
axios.interceptors.request.use(
  config => {
    dispatch({
    type: "SHOW_LOADER"
})
    return config;
  },
  error => {
     dispatch({
    type: "HIDE_LOADER"
})
    return Promise.reject(error);
  }
);

axios.interceptors.response.use(
  response => {
    dispatch({
    type: "HIDE_LOADER"
})
    return response;
  },
  error => {
    dispatch({
    type: "HIDE_LOADER"
})
    return Promise.reject(error);
  }
);
function GlobalLoader(){
    const [state,dispatch] = useContext(LoaderContext);
    return(
        <div>
            {
                state.loadStatus &&
                    <Loader
                    type = "Puff"
                    color = "#00BFFF"
                    height = {100}
                    width = {100}
                    timeout = {3000} />
            }
        </div>
    );
}

export default GlobalLoader;

如果需要更多信息,请告诉我。:)

1 个答案:

答案 0 :(得分:1)

使用axios.create(config)创建axios实例。在useEffect()中使用此实例来添加可以影响状态的拦截器(在这里,reducer太过强大了)。现在,到处使用实例,拦截器将导致状态更改。

注意:由于可以开始/结束多个请求,因此您应该使用一个计数器。根据要求增加,根据响应减少。如果计数器不是0,则说明应用程序正在加载。

const { useState, useCallback,useMemo, useRef, useEffect } = React;

const ax = axios.create(); // export this and use it in all your components

const useAxiosLoader = () => {
  const [counter, setCounter] = useState(0);
  
  const inc = useCallback(() => setCounter(counter => counter + 1), [setCounter]); // add to counter
  const dec = useCallback(() => setCounter(counter => counter - 1), [setCounter]); // remove from counter
  
  const interceptors = useMemo(() => ({
    request: config => (inc(), config),
    response: response => (dec(), response),
    error: error => (dec(), Promise.reject(error)),
  }), [inc, dec]); // create the interceptors
  
  useEffect(() => {
    // add request interceptors
    ax.interceptors.request.use(interceptors.request, interceptors.error);
    // add response interceptors
    ax.interceptors.response.use(interceptors.response, interceptors.error);
    return () => {
      // remove all intercepts when done
      ax.interceptors.request.eject(interceptors.request);
      ax.interceptors.request.eject(interceptors.error);
      ax.interceptors.response.eject(interceptors.response);
      ax.interceptors.response.eject(interceptors.error);
    };
  }, [interceptors]);
  
  return [counter > 0];
};

const GlobalLoader = () => {
    const [loading] = useAxiosLoader();
    
    return(
      <div>
      {
        loading ? 'loading' : 'not loading'
      }
      </div>
    );
}

// make a request by using the axios instance
setTimeout(() => {
  ax.get('https://swapi.co/api/people/1');
  ax.get('https://swapi.co/api/people/2');
  ax.get('https://swapi.co/api/people/3');
}, 1000);

ReactDOM.render(
  <GlobalLoader />,
  root
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.0/axios.js"></script>
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<div id="root"></div>