React TypeScript 16.8 如何使 useEffect() 异步

React TypeScript 16.8 How to make useEffect() async

为什么 useEffect() 不能使用 async-await?

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

我得到的错误是

Argument of type '() => Promise' is not assignable to parameter of type 'EffectCallback'.

Type 'Promise' is not assignable to type 'void | (() => void | undefined)'.

Type 'Promise' is not assignable to type '() => void | undefined'.

Type 'Promise' provides no match for the signature '(): void | undefined'.ts(2345)

不建议将效果声明为异步函数。 但是您可以在效果中调用异步函数,如下所示:

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

  genRandomKey();
}, []);

更多信息:React Hooks Fetch Data

您可以使用 use-async-effect 包,它提供了 useAsyncEffect 钩子:

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

您可以像这样使用 IIFE(自动执行的异步匿名函数):

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

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

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

为什么

useEffect 中使用异步函数使回调函数 return 成为 Promise 而不是 cleanup function

解决方案

useEffect(() => {
  const foo = async () => {
    await performPromise()
  };

  foo();
}, []);

IIFE

useEffect(() => {
  (async () => {
    await performPromise()
  })()
}, []);