我已经成功实现了一个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在这种情况下调用的正确方法是什么?