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

问题描述 投票:0回答:1

我需要: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;
};
reactjs redux jestjs react-hooks enzyme
1个回答
0
投票

返回之前,您可以在自定义钩子中将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;
};
© www.soinside.com 2019 - 2024. All rights reserved.