繁体   English   中英

如何在自定义挂钩上使用 useCallback?

[英]How to use useCallback on a custom hook?

我需要这个: const setError = useError(); 作为useEffect的依赖项,但由于此 function 也用于其他地方(在同一组件内),因此每当抛出错误时,我的useEffect api重新获取数据。

我应该禁用react-hooks/exhaustive-deps规则还是有办法解决这个问题? 如果我尝试将它包装在useCallback中,我会收到一个错误,即钩子只能在组件本身中使用。

编辑

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 function 与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;
};

使用上述内容,您可能会收到 ESLint 警告,将 dispatch 和 Sentry 作为依赖项添加到useCallback依赖项数组,您可以将它们添加到依赖项数组中,因为disptachSentry都不会改变

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM