在我的应用程序中,我正在一个API调用中进行多个API调用。我的意图是从代码中所示的5个电影API调用中同时获取title和release_date,并将标题和相关的发布日期彼此相邻(例如The Empire Strikes-1980-05-17 )。
为此,我正在使用map函数来遍历title数组并以li显示,但没有得到预期的输出。谁能建议我该怎么做?
App.js
import React, { Component } from 'react'
import charactersFile from "./data/characters.json"
import axios from 'axios';
import './App.css';
class App extends Component {
state = {
title: [],
release_date: []
}
componentDidMount() {
axios.get(`https://swapi.co/api/people/1/`)
.then(response => Promise.all([
axios.get(`https://swapi.co/api/films/2/`),
axios.get(`https://swapi.co/api/films/6/`),
axios.get(`https://swapi.co/api/films/3/`),
axios.get(`https://swapi.co/api/films/1/`),
axios.get(`https://swapi.co/api/films/7/`)
]))
.then(result => result.map(values =>
this.setState({
title: [this.state.title, values.data.title],
release_date: [this.state.release_date, values.data.release_date]
})))
}
render() {
console.log(this.state.title)
return (
<div className="App">
<ul>
{this.state.title.map(title => <li>{title}</li>)}
</ul>
{/* <h1>{this.state.title}</h1> */}
<h2>{this.state.release_date}</h2>
</div>
)
}
}
export default App
我的输出:
答案 0 :(得分:2)
与其将影片的数据存储在您尝试合并的两个不同的数组中,不如将相关数据存储在一个对象中,然后将每个渲染在一起。
class App extends React.Component {
state = {
movies: []
}
componentDidMount() {
axios.get(`https://swapi.co/api/people/1/`)
.then(response => Promise.all([
axios.get(`https://swapi.co/api/films/2/`),
axios.get(`https://swapi.co/api/films/6/`),
axios.get(`https://swapi.co/api/films/3/`),
axios.get(`https://swapi.co/api/films/1/`),
axios.get(`https://swapi.co/api/films/7/`)
]))
.then(result => result.map(values =>
this.setState({
movies: [
...this.state.movies,
{ title: values.data.title, release_date: values.data.release_date }
]
})))
}
render() {
return (
<div className="App">
<ul>
{this.state.movies.map(movie => (
<li>
<div className="title">{movie.title}</div>
<span>-</span>
<div>{movie.release_date}</div>
</li>
))}
</ul>
</div>
)
}
}