【问题标题】:How to use useCallback on a custom hook?如何在自定义挂钩上使用 useCallback?
【发布时间】:2020-08-18 03:09:44
【问题描述】:

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

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

编辑

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

【问题讨论】:

  • 能否展示useError的实现
  • @ShubhamKhatri 编辑了我的问题

标签: reactjs redux jestjs react-hooks enzyme


【解决方案1】:

您可以在返回之前将带有useCallback with an empty dependencysetError 函数包装在您的自定义钩子中,以便它只被创建一次

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 都不会改变

【讨论】:

    猜你喜欢
    • 2022-01-27
    • 2021-11-22
    • 2020-03-05
    • 1970-01-01
    • 1970-01-01
    • 2020-04-07
    • 2021-12-07
    • 1970-01-01
    • 2022-06-20
    相关资源
    最近更新 更多