我有一个 fetch api 调用,它返回一个非常大的数组,其中包含书籍和相关信息,我只需要标题、作者和相关段落。在componentDidMount()
我试图抓住这些值,并将它们推入一个新数组中,以对我的项目有意义的方式构造。
我成功地抓取并推送了这些值,但我无法维护嵌套结构。我希望书名和作者在顶部,然后将段落放在与书关联的嵌套数组中。我当前的代码只是将所有内容推到同一级别,没有嵌套。
在下面的代码中,我基本上想要this.state.dummyBooks
并且this.state.booksStructured
是相同的。
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
dummyBooks: [
{
title: "book title one",
author: "book author one",
passages: [
{
id: 1,
passage: "this is a passage",
},
{
id: 2,
passage: "this is another passage",
},
],
},
{
title: "book title two",
author: "book author two",
passages: [
{
id: 3,
passage: "this is a third passage",
},
{
id: 4,
passage: "this is yet another passage",
},
],
},
],
booksStructured: [],
};
}
componentDidMount() {
this.state.dummyBooks.map(bookObject => {
this.state.booksStructured.push({
bookTitle: bookObject.title,
bookAuthor: bookObject.author,
});
bookObject.passages.map(passageObject => {
this.state.booksStructured.push({
passageID: passageObject.id,
passageText: passageObject.passage,
});
});
});
}
render() {
console.log(this.state.booksStructured);
return <div>check the console</div>;
}
}
ReactDOM.render(<App />, document.querySelector("#app"));