【发布时间】:2021-04-28 17:44:51
【问题描述】:
我是初学者,正在努力更好地理解 API 调用。
我想调用一个检索所有书籍的圣经 API。 然后我需要调用与书相同的 api # 来检索请求书的所有章节。
然后我想显示书籍列表以及章节。
为此,我制作了一个实用函数,可以循环浏览书籍并返回章节。这就是它崩溃的地方。
我能够检索书籍并展示它们。但我对如何进行第二个 API 调用感到困惑。我不断收到无法序列化对象 Promise 的错误。
此外,在 Next 中控制台登录的最佳方式是什么?我不知道如何查看它被退回的内容。
这是我目前所拥有的:
export default function Home(props) {
console.log(props);
return (
<div className="container">
<div>{/** display books & chapters */}</div>
</div>
);
}
export async function getStaticProps() {
// get all books
const reqBooks = await fetch(`https://getbible.net/v1/web/books.json`);
const resBooks = await reqBooks.json();
// convert to array of objs
const books = await Object.entries(resBooks);
const chapters = await getChapters(books);
return {
props: {
books,
chapters,
},
};
}
// utility... loop through books and make api calls to get chapters for each book
async function getChapters(books) {
const chaptersArr = [];
books.map((item, idx) => {
//
let url = item[1].url;
let bookChapters = fetch(url).then(response => response.json().then(data => data));
arr.push(bookChapters);
});
return chaptersArr;
}
【问题讨论】:
-
使用 async/await 而不是 then 链(就像你已经拥有的代码一样)
标签: javascript reactjs fetch next.js