我正试图从视频游戏API中获取信息,并将其放入列表中。但是,API分为多个页面(我不知道有多少个页面)。
我尝试了以下解决方案:How to fetch data over multiple pages?
然后我尝试了另一种解决方案(下面的代码片段已更新),但这给了我一个错误:
已超过最大更新深度...
可能是因为它永远不会停止更新我的'currentPage'变量
经过数小时的调试,我放弃了。
这是我的文件:
import { Card, CardItem } from "native-base";
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
dataSource: [],
currentPage: 1
};
}
getUserFromApi = () => {
return fetch('https://api.rawg.io/api/games?page=' + this.state.currentPage +'&platforms=18', {
"method": "GET",
"headers": {
"x-rapidapi-host": "rawg-video-games-database.p.rapidapi.com",
"x-rapidapi-key": "495a18eab9msh50938d62f12fc40p1a3b83jsnac8ffeb4469f"
}
})
.then(response => response.json())
.then(responseJson => {
this.setState({
isLoading: false,
dataSource: this.state.dataSource.concat(responseJson.results)
});
})
.catch(error => console.log(error));
};
componentDidMount() {
this.getUserFromApi();
}
render() {
const { isLoaded, items } = this.state;
if (this.state.isLoading) {
return (
<View style={styles.progress}>
<ActivityIndicator size="large" color="#01CBC6" />
</View>
);
}
return (
<FlatList
data={this.state.dataSource}
onEndReached={ this.setState({ currentPage: this.state.currentPage + 1 }) }
答案 0 :(得分:0)
遍历API,递增currentPage
的值,直到没有结果返回(因此,指示列表的末尾)。
function fetchAllGamesFromAPI() {
let endOfList = false;
let items = [];
let currentPage = 1;
while(endOfList === false) {
const result = fetchGamesFromAPI(currentPage);
endOfList = !result.length;
items = [...items, ...result];
currentPage += 1;
}
return items;
}
当然,由于您(don't know how many there are).
会导致
当用户通过FlatList提供的API滚动到列表的末尾(或附近)时,获取其他数据。 https://reactnative.dev/docs/flatlist#onendreached
const onEndReached = () => {
this.setState({
currentPage = currentPage + 1;
})
fetchGamesFromAPI(currentPage);
};
<FlatList
...
onEndReached={ onEndReached } />