在React Native中从API的多个页面获取数据

时间:2020-08-04 21:50:33

标签: reactjs react-native api

我正试图从视频游戏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 }) } 

1 个答案:

答案 0 :(得分:0)

解决方案1 ​​

遍历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).会导致

解决方案2

当用户通过FlatList提供的API滚动到列表的末尾(或附近)时,获取其他数据。 https://reactnative.dev/docs/flatlist#onendreached


const onEndReached = () => {
    this.setState({
        currentPage = currentPage + 1;
    })
    
    fetchGamesFromAPI(currentPage);
};

<FlatList
    ...
    onEndReached={ onEndReached } />