【发布时间】:2020-12-03 11:42:43
【问题描述】:
我正在为 Hacker news 创建简单的克隆,我想使用 useEffect 并在其中返回 id,然后使用这些 id 获取前 50 个帖子。
问题在于fetchHackerNewsPosts 中的第二个函数,它不会等待它在postsArray 中添加数据,而是将其打印为空。
import React from "react";
import logo from "./logo.svg";
import "./App.css";
function App() {
const [posts, setPosts] = React.useState([]);
React.useEffect(() => {
let postsArray = [];
async function fetchHackerNewsPosts() {
try {
// it waits this function
let postsIDsArray = await fetch(
"https://hacker-news.firebaseio.com/v0/topstories.json"
)
.then((res) => res.json())
.then((result) => {
return result;
});
// it doesn't wait this function
await postsIDsArray.slice(0, 50).map((postId) => {
fetch(`https://hacker-news.firebaseio.com/v0/item/${postId}.json`)
.then((res) => res.json())
.then((result) => {
postsArray.push(result);
});
});
} catch (error) {
console.log(error);
}
}
fetchHackerNewsPosts();
console.log(postsArray);
}, []);
return (
<div className="p-10">
<header className="">
<h1> Hacker news API </h1>
</header>
<div className="bg-blue-600">list</div>
</div>
);
}
export default App;
【问题讨论】:
-
这将对您有所帮助:async-await-inside-arraymap
标签: reactjs