我正在使用 PokeAPI 进行 PokeDex 项目,并且可以使用您的帮助。在尝试处理从 API 接收到的 json 时,我遇到了两种看似不同的数组类型:
例如,我能够检索第一种类型数组的名称和 url,但无法和/或不确定如何检索bulbasaur 的类型值。
我认为这与我填充数组的不同方式有关,但不确定。
这是我的代码:
class App extends Component {
constructor() {
super();
this.state = {
pokemonArray: [],
pokemonInfoArray: [],
searchfield: '',
}
}
componentDidMount() {
this.fetchKantoDex()
}
// Fetches the pokemon that reside in Kanto.
fetchKantoDex = () => {
fetch('https://pokeapi.co/api/v2/pokemon?limit=10')
.then(response => response.json())
.then(data => this.setState({ pokemonArray: data.results}))
.then(this.fetchSinglePokemon)
}
// Is called by other fetch methods. Loops through and fetches the information pertaining to
// each pokeon fetched, and stores their info in a seperate array.
fetchSinglePokemon = () => {
let tempInfo = [];
for(let i = 0; i < this.state.pokemonArray.length;i++){
let url = this.state.pokemonArray[i].url;
fetch(url)
.then(response => response.json())
.then(pokedata => tempInfo.push(pokedata))
.then(pokedata => console.log(pokedata.results))
}
this.setState({ pokemonInfoArray: tempInfo})
// console.log(this.state.pokemonArray)
console.log(this.state.pokemonInfoArray)
}