惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

S
Secure Thoughts
罗磊的独立博客
T
The Blog of Author Tim Ferriss
人人都是产品经理
人人都是产品经理
博客园 - 叶小钗
Last Week in AI
Last Week in AI
美团技术团队
Google Online Security Blog
Google Online Security Blog
Application and Cybersecurity Blog
Application and Cybersecurity Blog
D
Docker
G
Google Developers Blog
大猫的无限游戏
大猫的无限游戏
酷 壳 – CoolShell
酷 壳 – CoolShell
小众软件
小众软件
月光博客
月光博客
L
LINUX DO - 最新话题
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
W
WeLiveSecurity
H
Heimdal Security Blog
Vercel News
Vercel News
SecWiki News
SecWiki News
Forbes - Security
Forbes - Security
Blog — PlanetScale
Blog — PlanetScale
Google DeepMind News
Google DeepMind News
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
www.infosecurity-magazine.com
www.infosecurity-magazine.com
TaoSecurity Blog
TaoSecurity Blog
T
Troy Hunt's Blog
A
About on SuperTechFans
C
Check Point Blog
S
Security Affairs
Hacker News - Newest:
Hacker News - Newest: "LLM"
AI
AI
WordPress大学
WordPress大学
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Help Net Security
Help Net Security
博客园_首页
The Last Watchdog
The Last Watchdog
S
SegmentFault 最新的问题
Hugging Face - Blog
Hugging Face - Blog
Security Archives - TechRepublic
Security Archives - TechRepublic
Engineering at Meta
Engineering at Meta
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
I
Intezer
K
Kaspersky official blog
M
MIT News - Artificial intelligence
J
Java Code Geeks
G
GRAHAM CLULEY
P
Palo Alto Networks Blog

博客园 - Sameen

上下文工程学习笔记 什么是vibe ? 什么是 embedding ? angular中asObservable是什么的,为什么需要用? vscode问题 document cookie JavaScript中的Date squash merge Element.scrollIntoView requestIdleCallback angular学习笔记 css斜条纹背景——linear-gradient 【转】过滤不可见字符 换电脑快捷同步vscode插件和配置 Git自动补全配置安装(Mac版本) Mac上看不到.git目录下的隐藏文件的解决方法 ts 问号点 ?. moment获取本月、上个月、近三个月时间段 iframe优缺点
[转]React hooks useEffect中如何使用异步函数(即如何使用async/await)
Sameen · 2022-12-09 · via 博客园 - Sameen

1. useEffect 的回调参数返回的是一个清除副作用的 clean-up 函数。因此无法返回 Promise,更无法使用 async/await

2.如何让useEffect支持async/await

2.1、方法一(推荐):useEffect中异步函数采用IIFE写法( Immediately Invoked Function Expression即立即调用的函数式表达式)

const MyFunctionnalComponent: React.FC = props => {
  useEffect(() => {
    // Using an IIFE
    (async function anyNameFunction() {
      await loadContent();
    })();
  }, []);
  return <div></div>;
};


2.2方法二:此时可以选择再包装一层 async 函数,置于 useEffect 的回调函数中,变相使用 async/await

const fetchMyAPI =async()=> {
  let response = await fetch('api/data')
  response = await res.json()
  dataSet(response)
}
 
useEffect(() => {
  fetchMyAPI();
}, []);


2.3方法三:在内部创建一个异步函数,等待getData(1)结果,然后调用setData():

useEffect(() => {
  const fetchMyAPI = async () =>{
      const data = await getData(1);
      setData(data)
  }
  fetchMyAPI();
}, []);

摘自:https://blog.csdn.net/zhongzk69/article/details/116266085