reactjs - 使用 axios 自定义 http 钩子
问题描述
我正在尝试创建我的第一个自定义钩子,但我不确定我是否在正确的轨道上。可能不是,这就是我问的原因。首先,我不确定取消令牌是否会像这样工作,或者当我在组件中实际使用这个钩子时是否需要使用它。
import { useState } from "react";
import Axios from "axios";
export default useApi = () => {
const [data, setData] = useState([]);
const [error, setError] = useState(false);
const [loading, setLoading] = useState(false);
const request = async () => {
const ourRequest = Axios.CancelToken.source();
setLoading(true);
try {
const response = await Axios(url, options);
setData(response.data);
setLoading(false);
} catch (error) {
setLoading(false);
setError(error);
}
return () => {
ourRequest.cancel();
};
};
return { data, error, loading, request };
};
解决方案
这看起来没问题,只是没有告诉 axios 关于 cancelToken 或适当地处理取消错误。文档的取消部分包含有关此过程的一些详细信息,我已将其折叠到您的示例中:
import { useState } from "react";
import axios from "axios";
export default useApi = () => {
const [data, setData] = useState([]);
const [error, setError] = useState(false);
const [loading, setLoading] = useState(false);
const request = async () => {
const source = axios.CancelToken.source();
setLoading(true);
try {
const response = await axios.get(url, { cancelToken: source.token });
setData(response.data);
setLoading(false);
} catch (error) {
if (axios.isCancel(error)) {
// don't update state in case component is dismounting
} else {
setLoading(false);
setError(error);
}
}
return () => {
source.cancel();
};
};
return { data, error, loading, request };
};
推荐阅读
- jhipster - jHipster 显示“发生错误 :-(” 在 Internet Explorer 中打开应用程序时,但在 chrome 浏览器中工作正常
- java - 如何指定该用户是否已共享我的应用 x 次?
- lua - Kong v1.0.2 的自定义插件已启用但未安装
- python - 如何摆脱python中的嵌套循环
- c# - 使用双泛型的 C# 类:当它们都应该相同时只给出一个?
- python - Python:针对不同特定工作人员的分布式任务队列
- r - 与 R 的字符串比较
- python - scrollintoview 没有滚动到元素(python)
- r - 如何在 R 中通过一个脚本多次预测一个变量?
- reactjs - 错误:操作必须是普通对象。使用自定义中间件进行非 api 调用更新的异步操作