【发布时间】:2021-07-26 21:43:02
【问题描述】:
因此,我正在学习 React,并被困在从两个不同的 API 获取数据并将数据显示到同一个表中。我可以显示来自第一个 API 的数据,我从中获取编号和名称,但是当我尝试显示来自第二个 API 的数据以获取流派时,它不再起作用了。我什至不确定我是否可以这样做,但希望有人可以提供帮助。
class Stops extends React.Component {
constructor () {
super()
this.state = {
books: [],
authors: []
}
}
componentDidMount () {
fetch('/url1')
.then((res) => {
res.json()
.then(data => this.setState({ books: data }))
})
fetch('/url2')
.then((response) => {
response.json()
.then(authorData => this.setState({authors: authorData }))
})
}
Displayauthors (authors) {
return authors.map((author) => (
<div key={author.authorId}>
{author.genre}
</div>
))
}
render () {
const books = this.state.books
return (
<div>
<table>
<thead>
<tr>
<th>number</th>
<th>name</th>
<th>Genre</th>
<th>Download book</th>
</tr>
</thead>
<tbody>
{
books.map((book) => (
<tr key={book.id}>
<td>{book.number}</td>
<td>{book.name}</td>
<td>{this.displayAuthors(this.state.authors)}</td>
<td><button type="button">Download</button></td>
</tr>
))
}
</tbody>
</table>
</div>
)
}
}
【问题讨论】:
标签: reactjs frontend backend display fetch-api