[英]react useEffect hook infinite loop caused by axios cancel token [react-hooks/exhaustive-deps]
In my react component I am using useEffect
to fetch data on the mount of component and each time that filters change.在我的反应组件中,我使用
useEffect
来获取组件安装和每次过滤器更改时的数据。 Everything works as it should but react-hooks/exhaustive-deps
throws warning that the fetcher function should be in the array of dependencies.一切正常,但
react-hooks/exhaustive-deps
会发出警告,提示提取器 function 应该在依赖项数组中。 By adding fetcher to dependencies list the app gets into an infinite loop.通过将 fetcher 添加到依赖项列表,应用程序进入无限循环。 The fetcher receives a new Axios cancel token on each run which causes an infinite loop of calls to fetcher.
fetcher 在每次运行时都会收到一个新的 Axios 取消令牌,这会导致对 fetcher 的调用无限循环。 How should I handle this situation, without disabling the rule?
在不禁用规则的情况下,我应该如何处理这种情况?
he fetcher function is outside of the useEffect
, cause another callback functions (passed to children) might call the fetcher.他 fetcher function 在
useEffect
之外,导致另一个回调函数(传递给孩子)可能会调用 fetcher。 eg a modal that can edit user and on successful editing calls fetcher to reload new users例如,可以编辑用户并在成功编辑时调用 fetcher 以重新加载新用户的模式
const [isLoading, setIsLoading] = React.useState<boolean>(false);
const [users, setUsers] = React.useState<IUser[]>([]);
const [filters, setFilters] = React.useState<ITableFilters>({...initFilters});
const fetcher = async (s: CancelTokenSource): Promise<void> => {
setIsLoading(true);
const params = { ...filters };
try {
const { data} = await fetchAllUsers({
params,
cancelToken: s.token
});
setUsers(data.users);
setIsLoading(false);
} catch (error) {
handleResponseError(error);// wchich checks axios.isCancel
setIsLoading(false);
}
}
React.useEffect(() => {
const source = axios.CancelToken.source();
// tslint:disable-next-line: no-floating-promises
fetcher(source);
return function cleanup() {
source.cancel();
};
}, [filters]);
You could use useCallback
, therefore the reference to the fetcher
should stay the same, not causing any more re-renders.您可以使用
useCallback
,因此对fetcher
的引用应该保持不变,不会导致更多的重新渲染。
const fetcher = useCallback(async (s: CancelTokenSource) => {
setIsLoading(true);
const params = { ...filters };
try {
const { data} = await fetchAllUsers({
params,
cancelToken: s.token
});
setUsers(data.users);
setIsLoading(false);
} catch (error) {
handleResponseError(error);// wchich checks axios.isCancel
setIsLoading(false);
}
}, [setIsLoading, setUsers, filters])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.