我需要:const setError = useError();
作为useEffect
中的依赖项,但是由于此函数也在其他地方(同一组件内)使用,因此每当引发错误时,我的useEffect api
都会重新获取数据。
我应该只禁用react-hooks/exhaustive-deps
规则还是可以解决此问题?如果尝试将其包装在useCallback
中,则会收到一个错误,指出只能在组件本身内使用挂钩。
edit
export const useError = (): ((error: any, title?: string) => void) => {
const dispatch = useDispatch();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const setError = (error: any, title = 'Error'): void => {
Sentry.captureException(error);
const bodyText = error.message || error;
const errorTitle = error.name || title;
dispatch(
setNotification({
type: notificationTypes.prompt,
title: errorTitle,
bodyText,
className: 'error',
show: true,
})
);
};
return setError;
};
返回之前,您可以在自定义钩子中将setError
函数包装为useCallback with an empty dependency
,以便仅创建一次]
export const useError = (): ((error: any, title?: string) => void) => {
const dispatch = useDispatch();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const setError = useCallback((error: any, title = 'Error'): void => {
Sentry.captureException(error);
const bodyText = error.message || error;
const errorTitle = error.name || title;
dispatch(
setNotification({
type: notificationTypes.prompt,
title: errorTitle,
bodyText,
className: 'error',
show: true,
})
);
}, []);
return setError;
};