我尝试用pokeapi.co创建PokemonList 然后我先获取/ pokemon /以获取/ pokemon / {pokemonName}的列表,然后再次循环获取/ pokemon /的详细信息,因为/ pokemon /仅提供名称
fetchData(){
fetch(this.state.urlState)
.then(response => response.json())
.then(responseJson => {
this.setState({
urlState: responseJson.next,
totalPokemon: responseJson.count
});
for (
let i = 0, p = Promise.resolve();
i < responseJson.results.length;
i++
) {
p = p.then(
_ =>
new Promise(resolve => {
fetch(
"https://pokeapi.co/api/v2/pokemon/" +
responseJson.results[i].name
)
.then(response => response.json())
.then(responseJson => {
newData = this.state.dataSource;
newData.push({
id: responseJson.id,
name: responseJson.name,
sprite: responseJson.sprites.front_default
});
this.setState({
totalFetchedData: this.state.totalFetchedData + 1,
dataSource: newData
});
resolve();
});
})
);
}
})
.catch(error => {
console.error(error);
});
}
这是我的fetchData函数
<FlatList
data={this.state.dataSource}
onEndReached={() => this.fetchData()}
onEndReachedThreshold={0.5}
renderItem={({ item }) => {
return (
<View>
<Text>
{pokeNumber} - {item.name}
</Text>
</View>
);
}}
extraData={this.state}
/>
这是我的FlatList组件,我发现onEndReached已触发,因为该列表缺少项目,因此即使第一次加载尚未完成,它也会触发onEndReached。 onEndReached是否有任何解决方法,它必须先等待我的fetchData完成才能获取另一个。
答案 0 :(得分:0)
对此问题进行了讨论,您可能会从the issue中找到几种可以应用的解决方案。
首先,您可以做的是在Github上遵循此人的解决方案,该解决方案使用FlatList上的onMomentumScrollBegin来防止未滚动事件的调用。
https://github.com/facebook/react-native/issues/14015#issuecomment-310675650
第二方法正在通过使用计时器(例如来自lodash debounce的debounce()来等待数据提取。但是此解决方案可能不起作用,因为它取决于互联网和处理速度。