programing

사용자 지정 후크에 콜백을 사용하는 방법?

prostudy 2022. 3. 11. 22:36
반응형

사용자 지정 후크에 콜백을 사용하는 방법?

난 이게 필요해:const setError = useError();에 의존하여useEffect, 그러나 이 기능은 다른 장소에서도 사용되기 때문에 (동일한 구성 요소 내에서) 오류가 발생할 때마다 myuseEffect 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와의 기능을 하다.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;
};

위와 같이 디스패치와 Sentry를 에 종속시키기 위해 ESLint 경고를 받을 수 있다.useCallback종속성 어레이, 다음 중 어느 것도 종속성 어레이에 추가하지 않으므로 이러한 어레이를 종속성 어레이에 추가할 수 있음disptach또는Sentry변했을 것이다

참조URL: https://stackoverflow.com/questions/61579564/how-to-use-usecallback-on-a-custom-hook

반응형