【问题标题】:problem with using axios interceptors in react在反应中使用 axios 拦截器的问题
【发布时间】:2021-07-04 01:00:30
【问题描述】:

我想在使用 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 中有一个

标记,我用它来显示我从./axiosInstance.js 获取的fetching 变量的值。它的值永远不会改变为真,它总是假的。

<p>{ fetching ? "true": "false" }</p>

【问题讨论】:

    标签: javascript reactjs axios xmlhttprequest interceptor


    【解决方案1】:
    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 作为状态。 它会工作的。

    【讨论】:

      猜你喜欢
      • 2021-11-07
      • 2021-02-11
      • 2019-02-11
      • 2019-06-26
      • 2020-02-28
      • 2019-03-15
      • 2023-04-06
      • 2022-01-25
      • 2020-09-28
      相关资源
      最近更新 更多