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

Xee*_*een 9 reactjs jestjs redux enzyme react-hooks

我需要这个:const setError = useError();作为 中的依赖项useEffect,但由于此函数也在其他地方使用(在同一组件内),因此每当抛出错误时,我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;
};
Run Code Online (Sandbox Code Playgroud)

Shu*_*tri 5

您可以在返回之前将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;
};
Run Code Online (Sandbox Code Playgroud)

通过上述内容,您可能会收到 ESLint 警告,要求将调度和 Sentry 添加为useCallback依赖项数组的依赖项,您可以将它们添加到依赖项数组中,因为两者都disptach不会Sentry改变