当前位置:网站首页>为什么不能直接在 useEffect 中使用 async
为什么不能直接在 useEffect 中使用 async
2022-04-22 18:49:00 【小鑫】
在代码中,我们会使用 async/await 从第三方 API 获取数据。如果你对 async/await 熟悉的话,你会知道,每个 async 函数都会默认返回一个隐式的 promise。但是,useEffect 不应该返回任何内容。所以你会在控制台日志中看到以下警告:
Warning: An effect function must not return anything besides a function, which is used for clean-up. It looks like you wrote useEffect(async () => ...) or returned a Promise. Instead, write the async function inside your effect and call it immediately:
这就是为什么不能直接在 useEffect 中使用 async 函数的原因。因此,我们可以不直接在 useEffect 里使用用 async 函数,需要把函数提取出来,像下面这样:
import React, { useState, useEffect } from 'react';
import axios from 'axios';
function App() {
const [data, setData] = useState({ hits: [] });
const fetchData = async () => {
const result = await axios('http://localhost/api/v1/search?query=redux');
setData(result.data);
};
useEffect(() => {
fetchData();
}, []);
return (
<ul>
{data.hits.map(item => (
<li key={item.objectID}>
<a href={item.url}>{item.title}</a>
</li>
))}
</ul>
);
}
export default App;
版权声明
本文为[小鑫]所创,转载请带上原文链接,感谢
https://cloud.tencent.com/developer/article/1985964
边栏推荐
- Storage network request log
- kettle庖丁解牛第13篇之XML文件输入
- [drive] TX2 transplants EC20 startup module
- [fundamentals of interface testing] Chapter 11 | detailed explanation of postman associated interface and batch execution use case set
- 旅游产品分析:要出发周边游
- jsp学习(八.JDBC与文件上传处理的项目)
- 聊聊缓存布尔值踩到的坑
- 大话测试数据(一)
- 视频知识点(16)- 如何将y4m文件转换成yuv文件?
- PHP 零基础入门笔记(12):数组 array
猜你喜欢
随机推荐
Storage network request log
062 反序列化漏洞
.net core 中使用IAsyncExceptionFilter 捕获全局异常,统一返回信息
What does naas, a charging service provider, rely on to rise without building piles?
.net core 中配置文件映射到类
Type description file of module code
Jsonobject data guarantee order of fastjson
kettle庖丁解牛第13篇之XML文件输入
【Spark】(task6)Spark RDD完成统计逻辑
PHP 零基础入门笔记(12):数组 array
【Proteus仿真】51单片机制作简易计算器+ LCD1602显示
企业沟通软件与其他通信对比的优势有哪些
nodejs如何预防xss攻击
.net core 多项目中使用EFCore
jsp学习(八.JDBC与文件上传处理的项目)
【驱动】TX2移植EC20启动模块
PCB Layout Stackup setting
基于SSM框架开发OA企业在线办公系统项目教程-附源码-毕业设计
The sandbox has entered into a cooperative relationship with apex athetes
Use bitnami PostgreSQL docker image to quickly set up stream replication clusters









