如何解决在反应中使用 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
作为状态。
它将起作用。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。