首页 > 解决方案 > 使用 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 };
};

标签: reactjsaxios

解决方案


这看起来没问题,只是没有告诉 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 };
};

推荐阅读