reactjs - 从 useEffect 返回承诺
问题描述
我正在阅读文章https://www.robinwieruch.de/react-hooks-fetch-data。
它提供了以下 2 个片段来演示如何处理 useEffect 中的承诺。第一个会引发错误,而第二个不会。
第一个片段 -
useEffect(async () => {
const result = await axios(
'https://hn.algolia.com/api/v1/search?query=redux',
);
setData(result.data);
}, []);
第二个片段 -
useEffect(() => {
const fetchData = async () => {
const result = await axios(
'https://hn.algolia.com/api/v1/search?query=redux',
);
setData(result.data);
};
fetchData();
}, []);
为什么第二个不抛出错误,当fetchdata()
被调用时它会返回一个promise,因此也会返回一个promise useEffect
。第二个片段与第一个片段有何不同?
解决方案
You can only return nothing or a cleanup function for useEffect hook. The reason the first snippet is throwing an error is because you marked the function async and the functions that are marked async will always return a promise.
//The function is marked async
useEffect(async () => {
const result = await axios(
'https://hn.algolia.com/api/v1/search?query=redux',
);
setData(result.data);
}, []);
It breaks the rule of returning either nothing or a cleanup function.
However In the second snippet, you are using useEffect function to call an async function, but since the useEffect function itself is not async, that means it is not returning a promise
//this is not marked async
useEffect(() => {
const fetchData = async () => {
const result = await axios(
'https://hn.algolia.com/api/v1/search?query=redux',
);
setData(result.data);
};
fetchData();
}, []);
推荐阅读
- node.js - nodejs url解析返回一个额外的未定义对象
- sql - SQL Server:从动态值表中选择列不包含任何值的所有行
- javascript - javascript:使工厂项目在包含音乐专辑集的字段上显示正确的值
- git - 在解决了我的分支变基的所有冲突之后,我做了“git rebase --continue”,我得到了“没有变基正在进行?” . 接下来我该怎么办?
- gradle - Kotlin 多平台库项目上传问题 - POM 多个工件
- android - 奖励视频违反 Google Admob 隐私政策?
- python-3.x - 寻找与准确的深度学习编译代码不同的准确率输入
- python - face_recognition.py:使用多个已知图像进行人脸检测。IndexError:列表索引超出范围
- ios - 自动将 UIView 的角半径设置为视图宽度的一半
- javascript - 即使我们确切地知道连接的路线,缓存 ICE 候选和 sdp 是否也不起作用?