2017-04-11 48 views
0

我正在使用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

希望你們能幫助!

+3

你看着抖? –

+0

你可能避免加載時,作出新的要求,但跟蹤他們所要求的口袋妖怪。當服務器響應回來,如果不是他們所要求的最新寵物小精靈,火了最新的請求。 – IrkenInvader

+0

[這可能不錯](https://github.com/bvaughn/debounce-decorator),可以讓你在你的課堂上拋出一個小修飾器,雖然 – corvid

回答

1

你可以使用防抖功能。這將允許函數在給定的時間段內只運行很多次。

function debounce(fn, wait) { 
    let timeout; 
    return (...args) => { 
    const waitFn =() => { 
     timeout = clearTimeout(timeout); 
     fn(...args); 
    }; 
    if (!timeout) { 
     timeout = setTimeout(waitFn, wait); 
    } 
    }; 
} 

// this will run the showDetails function only once every 500ms 
this.showDetails = debounce(this.showDetails.bind(this), 500); 
0

在additiona到@ realseanp的答案,你可以嘗試節流

function throttle(duration, fn) { 
    let inProgress; 
    return() => { 
    if (inProgress) { 
     clearTimeout(inProgress); 
    } 
    inProgress = setTimeout(fn, duration); 
    }; 
} 

window.addEventListener('keydown', throttle(500,() => console.log('keydown')), false);