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())}, [])返回 (...
我得到的错误是
<块引用>'() => 类型的参数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屋!