React TypeScript 16.8 如何使 useEffect() 异步 [英] React TypeScript 16.8 How to make useEffect() async

查看:53
本文介绍了React TypeScript 16.8 如何使 useEffect() 异步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我得到的错误是

<块引用>

'() => 类型的参数Promise' 不可分配给类型为 'EffectCallback' 的参数.

<块引用>

类型 'Promise' 不可分配给类型 'void |(() => void | undefined)'.

<块引用>

类型 'Promise' 不可分配给类型 '() =>;无效 |未定义'.

<块引用>

类型 'Promise' 不匹配签名 '(): void |未定义'.ts(2345)

解决方案

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

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

更多信息:React Hooks 获取数据

Why can't useEffect() use async-await?

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

The error I get is

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)

解决方案

Declaring the effect as async function is not recommended. But you can call async functions within the effect like following:

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

  genRandomKey();
}, []);

More here: React Hooks Fetch Data

这篇关于React TypeScript 16.8 如何使 useEffect() 异步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆