【发布时间】:2021-01-14 01:22:19
【问题描述】:
我正在浏览文章https://www.robinwieruch.de/react-hooks-fetch-data。
它给出了下面2个sn-ps来演示如何处理useEffect中的promise。第一个会抛出错误,而第二个不会。
第一个 sn-p -
useEffect(async () => {
const result = await axios(
'https://hn.algolia.com/api/v1/search?query=redux',
);
setData(result.data);
}, []);
第二个sn-p-
useEffect(() => {
const fetchData = async () => {
const result = await axios(
'https://hn.algolia.com/api/v1/search?query=redux',
);
setData(result.data);
};
fetchData();
}, []);
为什么第二个不抛出错误,当fetchdata()被调用时它会返回一个promise,因此useEffect也会返回一个promise。第二个 sn-p 和第一个有什么不同?
【问题讨论】:
-
when fetchdata() is called it will return a promise, and thus a promise will be returned from useEffect too.号 -
第一条语句抛出什么错误?
-
两者都返回
undefined。一个 useEffect 函数根本不能是async
标签: reactjs react-hooks