在反应中使用 axios 拦截器的问题

问题描述

我想在使用 axios 发出和发送请求时获得获取状态。我认为我可以通过使用 axios 拦截来实现这一点。我试试这个代码

./axiosInstance.js

let fetching = false;

const axiosInstance = axios.create();

axiosInstance.interceptors.request.use(config => { 
    fetching = true;
    console.log("first log: ",fetching);
    return config;
},() => { fetching = false });

axiosInstance.interceptors.response.use(() => { 
    console.log("second log: ",fetching);
    fetching = false;
    console.log("third log: ",fetching);
});

export { fetching,axiosInstance };

这就是我使用自己创建的 axios 实例发出和发送请求的方式:

./component.js

import { fetching,axiosInstance } from "./axiosInstance";

const Component = () => {

    const sendRequest = () => {
        axiosInstance.get("someUrl:somePort/");
    };

    return (
        <>
            <button type="button" onClick={ sendRequest }>click</button>
            <p>{ fetching ? "true": "false" }</p>
        </>
    );
}

export default Component;

但问题是,这行不通。我按预期登录 ./axiosInstance.js

first log: true
second log: true
third log: false

但是我在 ./component.js 中有一个

标记,我用它来显示从 {{1} 获取fetching 变量的值}}。并且它的值永远不会改变为真,它总是假的。

./axiosInstance.js

解决方法

import {useState} from 'react';

const [fetching,setFetching] = useState(false);

const axiosInstance = axios.create();

axiosInstance.interceptors.request.use(config => { 
    setFetching(true);
    console.log("first log: ",fetching);
    return config;
},() => { fetching = false });

axiosInstance.interceptors.response.use(() => { 
    console.log("second log: ",fetching);
    setFetching(false);
    console.log("third log: ",fetching);
});

export { fetching,axiosInstance };

您可以使用 fetching 作为状态。 它将起作用。