简体   繁体   English

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

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

I need this: const setError = useError();我需要这个: const setError = useError(); as a dependency in useEffect , but since this function is used in other places as well (within the same component), whenever an error is thrown, my useEffect api re-fetches data.作为useEffect的依赖项,但由于此 function 也用于其他地方(在同一组件内),因此每当抛出错误时,我的useEffect api重新获取数据。

Should I just disable the react-hooks/exhaustive-deps rule or is there some way out of this?我应该禁用react-hooks/exhaustive-deps规则还是有办法解决这个问题? If I try to wrap it in useCallback I get an error that hooks can only be used within the component itself.如果我尝试将它包装在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;
};

You can wrap the setError function with useCallback with an empty dependency in your custom hook before returning so that it is created only once您可以在返回之前将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;
};

With the above you might get a ESLint warning to add dispatch and Sentry as dependency to useCallback dependency array, you can add them to the dependency array since neither of disptach or Sentry would change使用上述内容,您可能会收到 ESLint 警告,将 dispatch 和 Sentry 作为依赖项添加到useCallback依赖项数组,您可以将它们添加到依赖项数组中,因为disptachSentry都不会改变

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

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