调用PokeAPI后执行.map方法报错is not a function问题咨询
问题根因
- 你调用的
https://pokeapi.co/api/v2/pokemon/ditto接口返回的是单个宝可梦的对象,不是数组。map是数组专属方法,普通对象调用自然会报pokemons.map is not a function错误。 - 你声明了
fetchPokemon是async函数,但没有返回fetch产生的Promise,也没有使用await处理异步逻辑,导致提交表单时调用fetchPokemon().then()时,then回调会在接口请求完成前就执行,此时pokemons还没被赋值为接口返回值。
修复方案
场景1:仅查询单个宝可梦,不需要用map方法,直接取对象属性即可
修改后的JS代码:
const result = document.getElementById('result'); const form = document.querySelector('form'); // 单个宝可梦不用声明为数组 let pokemon = null; async function fetchPokemon(keyword = 'ditto') { // 这里返回Promise,方便后续调用时等待请求完成 return fetch(`https://pokeapi.co/api/v2/pokemon/${keyword}`) .then((res) => res.json()) .then((data) => (pokemon = data)); }; fetchPokemon(); function pokemonDisplay() { // 判空避免无数据时报错 if (!pokemon) return // 单个对象直接取属性,不需要调用map result.innerHTML = ` <h2>${pokemon.forms[0].name}</h2> ` } form.addEventListener('submit', (e) => { e.preventDefault(); // 读取用户输入的搜索关键词 const keyword = document.getElementById('search').value.trim() || 'ditto' fetchPokemon(keyword).then(() => pokemonDisplay()); }) console.log(result);
场景2:需要查询宝可梦列表用map遍历
要调用返回数组的列表接口,例如https://pokeapi.co/api/v2/pokemon?limit=20,该接口返回的results字段才是宝可梦数组,适配对应取值逻辑即可。
内容的提问来源于stack exchange,提问作者dgrammont
相关产品推荐
相关产品推荐

