【发布时间】:2019-06-17 17:17:01
【问题描述】:
我尝试使用pokeapi.co 创建 PokemonList 我首先获取 /pokemon/ 以获取 /pokemon/{pokemonName} 的列表,然后再次循环以获取我的数据源的详细信息,因为 /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 完成,然后再获取另一个。
【问题讨论】:
标签: react-native react-native-android react-native-ios react-native-flatlist