如何正确调用 useFetch 函数?

IT技术 reactjs react-hooks
2021-05-05 06:59:16

我已经成功实现了一个useFetch调用 API 端点函数。如果我将这样的代码添加到像这样的功能性 React 组件的根,它会完美地工作:

  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]);

但得到了同样的错误。

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

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

我仍然遇到同样的错误。

特别是在最后两个案例中,我觉得我遵循 Hooks 规则,但显然没有!

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

1个回答

我想你是这样称呼的useFetch,对吧?

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

如果是真的,这是错误的。看看这个链接

🔴 不要调用事件处理程序。

你可以这样实现:

// 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);
  ...
}

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