我正在按照自己的方式进行API练习,并且想知道为什么“ id”元素不断向其中添加不必要的值。例如,我将首先搜索“ Pikachu”,整个结果将返回Pikachu(data.id为25)及其统计信息。点击下一个按钮(事件侦听器)后,id成功地增加到列表中的下一个神奇宝贝Raichu(data.id为26);其统计信息也可以正确显示。这种情况完美地起作用!
然后我将搜索另一个神奇宝贝“ Charmander”,并且id值现在为“ 4”。但是,问题是在我进行第二次搜索然后再次单击“下一步”按钮后开始的。该ID将从Raichu的ID开始,然后将进一步递增,同时也从“ 4”递增。因此,我的控制台日志开始看起来像这样:在第二次搜索后,每按一次,“ 4”,“ 27”,“ 5”,“ 28”,“ 6”就出现了,而不是弹出Charizard,而是在Raichu之后放了一些宠物小精灵弹出。
我声明的内容有误还是写得太复杂?我想我期望每次搜索神奇宝贝时都会刷新“ id”变量,但似乎它一直在继续。
function pokemonInfo(e) {
e.preventDefault();
const searchValue = search.value
fetch(`https://pokeapi.co/api/v2/pokemon/${searchValue}`)
.then(res=>res.json())
.then(data => {
const pokemon = data
console.log(pokemon)
let id = pokemon.id
console.log(id)
next.addEventListener('click', ()=>{
id++
console.log(id)
fetch(`https://pokeapi.co/api/v2/pokemon/${id}`)
.then(res=>res.json())
.then(data => {
const pokemon = data
pokeName(pokemon);
sprtFrnt(pokemon);
sprtBck(pokemon);
firstType(pokemon);
secondType(pokemon);
})
})
//Other Functions
pokeName(pokemon);
sprtFrnt(pokemon);
sprtBck(pokemon);
firstType(pokemon);
secondType(pokemon);
})
.catch(err => {
const notFound ='This Pokemon is not found!'
})
}
答案 0 :(得分:1)
正在发生的事情是,每次进行新搜索时,您都在下一个按钮上添加了新的事件侦听器。您应该将id的值保存在函数范围之外,并且只应将事件侦听器添加到next按钮一次。
您的代码似乎还会重复很多
这样的事情可以避免重复,并阻止您添加额外的侦听器:
const ENDPOINT = 'https://pokeapi.co/api/v2/pokemon/';
let id = 1;
// Code where you define what next and search are ...
next.addEventListener('click', ()=>{
fetchNewPokemon(id + 1);
});
function pokemonInfo(e) {
e.preventDefault();
fetchNewPokemon(search.value);
}
function fetchNewPokemon(searchValue) {
fetch(`${ENDPOINT}${searchValue}`)
.then(res=>res.json())
.then(pokemon => {
id = pokemon.id;
//Other Functions
pokeName(pokemon);
sprtFrnt(pokemon);
sprtBck(pokemon);
firstType(pokemon);
secondType(pokemon);
})
.catch(err => {
const notFound ='This Pokemon is not found!'
})
}
仔细阅读作用域/闭包可能有助于您理解为什么代码未按预期运行的原因。 MDN撰写了关于Closures的大量文章,以及嵌套它们如何影响您的代码。