简体   繁体   English

FlatList-在获取更多内容而没有剩余项目时循环项目-React Native

[英]FlatList - loops items when fetching more with no items left - React Native

I am fetching data from the api and fetch more data every 15 items. 我正在从api获取数据,每15个项目获取更多数据。 However, when there is no more data left, it's still trying to fetch more and gives an error that next item doesn't exist or just loops the items from 0. How can I stop fetching the data on the last item from the database? 但是,当没有剩余数据时,它仍在尝试获取更多数据,并给出一个错误,即下一个项目不存在或仅从0开始循环这些项目。如何停止从数据库中获取上一个项目的数据? Here is my code: 这是我的代码:

export default class One extends React.PureComponent {
  constructor(props) {
    super(props);
    this.fetchMore = this._fetchMore.bind(this);
    this.fetchData = this._fetchData.bind(this);
    this.state = {
      isLoading: true,
      isLoadingMore: false,
      _data: null,
      _dataAfter: '',
      accessToken: "",
    };
  }
async componentWillMount() {
try {
      let accessToken = await AsyncStorage.getItem(ACCESS_TOKEN).then(JSON.parse);
      if(!accessToken) {
          this.redirect('login');

      } else {
        this.setState({accessToken: accessToken})

      }
    } catch(error) {
        console.log("Something went wrong");
        this.redirect('login');
    }  

     this.fetchData(responseJson => {
      const data = responseJson;
      this.setState({
        isLoading: false,
        _data: data,
        _dataAfter: responseJson.after,
      });
    });
}    
  _fetchData(callback) {
      const params = this.state._dataAfter !== ''
      ? `&after=${this.state._dataAfter}`
      : '';
    fetch(`https://mywebsite.com/posts?limit=15${params}`,
         {
         method: 'GET',
         headers: {
           'Accept': 'application/json',
           'Content-Type': 'application/json',
           'Authorization': "Bearer " + this.state.accessToken.token,
         }
    })
      .then(response => response.json())
      .then(callback)
      .catch(error => {
        console.error(error);
      });
  }
 _fetchMore() {
    this.fetchData(responseJson => {
      const data = this.state._data.concat(responseJson);
      this.setState({
        isLoadingMore: false,
        _data: data,
        _dataAfter: responseJson.after,
      });
    });
  }

  render() {
      if (this.state.isLoading) {
      return (
        <View style={styles.container}>
          <ActivityIndicator size="large" />
        </View>
      );
    } else {
      return (  
        <FlatList
        numColumns={1}
          data={this.state._data}
          renderItem={({item}) => {
            return (
                <View>
                <Text>
                {item.name}
              </Text>
           </View>  
            );
          }}
         onEndReached={() =>
            this.setState({ isLoadingMore: true }, () => this.fetchMore())}
          ListFooterComponent={() => {
            return (
              this.state.isLoadingMore &&
              <View style={{ flex: 1, padding: 10 }}>
                <ActivityIndicator size="small" />
              </View>
            );
          }}
          keyExtractor={(item, index) => index}
        />
      );
  }
}
}

Just make params for notice that no items left 只是设置参数以通知没有剩余项目

Change state to 将状态更改为

this.state = {
  isLastData: false, // this new var
  isLoading: true,
  isLoadingMore: false,
  _data: null,
  _dataAfter: '',
  accessToken: "",
};

Make fetch more like this 使获取更像这样

_fetchMore() {
    this.fetchData(responseJson => {
      const data = this.state._data.concat(responseJson.children);
      this.setState({
        isLastData: data.length > 0 ? false : true, 
        isLoadingMore: false,
        _data: data,
        _dataAfter: responseJson.after,
      });
    });
  }

Add logic to onEndReached 向onEndReached添加逻辑

            onEndReached={
            () => {
                if (! this.state.isLastData) {
                    this.setState({ isLoadingMore: true }, () => this.fetchMore())
                }
            }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM