我正在使用react和pokeAPI来做一个小型只为乐趣项目(pokedex)。快速点击创建了太多的请求
在应用程序的用户可以点击一个口袋妖怪和应用程序将获取该宠物小精灵,并显示在模式对话框的其他信息。
问题是这样的:在模式框中,如果用户点击其中一个箭头快速点击api,则会在每个模式框中左右箭头更改为前一个和下一个小宠物时间和点击停止时,用户必须等待所有先前的承诺解决。
我不想禁用方法或同时加载的按钮,因为它应该可以通过口袋妖怪运行。我基本上只是想拒绝以前的承诺,如果有新的承诺。这可能吗?
这里是提取小宠物的方法:
showDetails(pokemon){
//check if the pokemon is already is state
const statePokemon = this.state.pokemon.find(p => {
return p.name === pokemon;
});
if(!statePokemon) {
//set loading and pass the pokemon as a string
//to show which pokemon is being fetched
this.setState({
pokemonLoading : true,
pokemonFetched : false,
showing : pokemon,
});
let pokemonArr = [...this.state.pokemon];
let newPokemon = {};
fetch(`http://pokeapi.co/api/v2/pokemon/${pokemon}`)
.then(response => response.json())
.then(response => {
pokemonArr.push(response);
newPokemon = response;
})
.then((_) => {
//don't update state with new pokemon
//if user has closed modal while loading
if (this.state.showing) {
this.setState({
pokemon : pokemonArr,
pokemonLoading : false,
pokemonFetched : true,
showing : newPokemon,
});
}
});
} else {
//set showing with pokemon from state
//without making a new fetch
this.setState({
showing : statePokemon,
pokemonFetched : true,
});
}
}
该项目的回购协议是here
希望你们能帮助!
你看着抖? –
你可能避免加载时,作出新的要求,但跟踪他们所要求的口袋妖怪。当服务器响应回来,如果不是他们所要求的最新宠物小精灵,火了最新的请求。 – IrkenInvader
[这可能不错](https://github.com/bvaughn/debounce-decorator),可以让你在你的课堂上抛出一个小修饰器,虽然 – corvid