【发布时间】:2021-12-16 10:18:56
【问题描述】:
我读到有人在不同的网站上发布过这个问题,但他们的错误与我的不同。我正在使用通用的useFetch 自定义钩子,它不会影响任何 atm。只是使用它会导致无限循环,我不明白为什么。
这是自定义钩子:
const useFetch = (config: AxiosRequestConfig) => {
const [response, setResponse] = useState<AxiosResponse | null>(null);
const [error, setError] = useState<any>(null);
const [loading, setLoading] = useState<boolean>(true);
config.baseURL = config.baseURL || "/api";
useEffect(() => {
axios
.request(config)
.then((res) => setResponse(res))
.catch((err) => setError(err))
.finally(() => setLoading(false));
}, [config]);
return { response, error, loading };
};
现在我在组件中所做的只是将一个变量初始化为useFetch({url: '/endpoint'})。
这会导致无限循环。如果我控制台记录结果,页面就会填满。如果我删除分配给 useFetch 它就会消失......
任何想法我做错了什么?
谢谢!
【问题讨论】:
标签: reactjs react-hooks infinite-loop