bestsource

React TypeScript 16.8 useEffect() 비동기화 방법

bestsource 2023. 2. 28. 23:39
반응형

React TypeScript 16.8 useEffect() 비동기화 방법

할 수 없는 이유useEffect()async-module을 사용하시겠습니까?

const Home: React.FC = () => {
    
    useEffect(async () => {
        console.log(await ecc.randomKey())
    }, [])
    
    return (
    ...

내가 받는 오류는

'() = > Promise' 형식의 인수는 'EffectCallback' 형식의 매개 변수에 할당할 수 없습니다.

'Promise' 유형은 'type | (() => void | undefined)' 유형에 할당할 수 없습니다.

'Promise' 유형은 '() => void | defined' 유형에 할당할 수 없습니다.

'Promise'를 입력하면 시그니처 '(: void | defined)'와 일치하지 않습니다.ts(2345)

효과를 비동기 함수로 선언하는 것은 권장되지 않습니다.다만, 다음과 같은 효과로 비동기 함수를 호출할 수 있습니다.

useEffect(() => {
  const genRandomKey = async () => {
    console.log(await ecc.randomKey())
  };

  genRandomKey();
}, []);

추가 정보: 리액트 훅 데이터 가져오기

IIFE(스스로 실행되는 비동기 어나니머스 함수)를 다음과 같이 사용할 수 있습니다.

useEffect(() => {
    // Some synchronous code.

    (async () => {
        await doSomethingAsync();
    })();

    return () => {
        // Component unmount code.
    };
}, []);

이 패키지를 사용하면,useAsyncEffect후크:

useAsyncEffect(async () => {
  await doSomethingAsync();
});

언급URL : https://stackoverflow.com/questions/57238928/react-typescript-16-8-how-to-make-useeffect-async

반응형