如何正确调用useFetch函数? [英] How to correctly call useFetch function?

查看:8
本文介绍了如何正确调用useFetch函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经成功实现了调用API Endpoint的useFetch函数。如果我将这样的代码添加到如下所示的功能性Reaction组件的根中,它就能完美地工作:

  const [{ data, isLoading, isError }] = useFetch(
    'http://some_api_endpoint_path'
  );
export const useFetch = (url) => {
  const [data, setData] = useState();
  const [isLoading, setIsLoading] = useState(false);
  const [isError, setIsError] = useState(false);

  useEffect(() => {
    const fetchData = async () => {
      setIsError(false);
      setIsLoading(true);
      try {
        const response = await axios.get(url);
        setData(response.data);
      } catch (error) {
        setIsError(true);
      }
      setIsLoading(false);
    };

    fetchData();
  }, [url]);
  return [{ data, isLoading, isError }];
};
但假设我想检查新输入的username是否存在,比如在激发输入元素的onBlur事件时。当我尝试实现此功能时,收到以下错误:

React Hook "useFetch" is called in function "handleBlur" which is neither a React function component or a custom React Hook function  react-hooks/rules-of-hooks

我甚至尝试过这种方法:

  const [isChanged, setIsChanged] = useState(false);

  useEffect(() => {
    useFetch(
      'http://some_api_endpoint_path'
    );
  }, [isChanged]);

但收到相同的错误。

然后我尝试了这个简化的版本,它没有做任何有用的事情,但我在测试Reaction Hooks规则:

  useEffect(() => {
    useFetch(
      'http://some_api_endpoint_path'
    );
  }, []);

但我仍然收到相同的错误。

特别是在后两个案例中,我觉得我是在遵循钩子规则,但显然不是!

在这种情况下,调用useFetch的正确方式是什么?

推荐答案

我想您是这样调用useFetch的,对吧?

const onBlur = () => {
  const [{ data, isLoading, isError }] = useFetch(
    'http://some_api_endpoint_path'
  );
  ...
}

如果为真,则这是错误的。签出此link

🔴不调用事件处理程序。

您可以这样实现:

// Pass common initial for all fetches.
export const useFetch = (awsConfig, apiRoot, apiPathDefault) => {
  const [data, setData] = useState();
  const [isLoading, setIsLoading] = useState(false);
  const [isError, setIsError] = useState(false);

  // Just pass the variables that changes in each new fetch requisition
  const fetchData = async (apiPath) => {
      setIsError(false);
      setIsLoading(true);
      try {
        const response = await axios.get(apiRoot + apiPath);
        setData(response.data);
      } catch (error) {
        setIsError(true);
      }
      setIsLoading(false);
    };

  useEffect(() => {
    fetchData(apiRoot + apiPathDefault);
  }, [awsConfig, apiRoot, apiPathDefault]);

  return [{ data, isLoading, isError }, fetchData];
};

每当您想要再次提取时,只需调用fetchData

const [{ data, isLoading, isError }, fetchData] = useFetch(API_ROOT(), appStore.awsConfig, defaultPath);

const onBlur = () => {
  fetchData(newPath);
  ...
}

我使用了阿波罗团队在创建useLazyQuey时使用的相同原则(请打开此link并搜索useLazyQuery)。另外,请注意,在调用钩子时,我传递了所有公共变量和不可变变量,而在单次FETCH中只传递了可变变量。

这篇关于如何正确调用useFetch函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆