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

时间:2017-11-03 21:35:05

标签: javascript reactjs react-native fetch react-native-flatlist

我从api获取数据并每15个项目获取更多数据。但是,当没有剩余数据时,它仍然试图获取更多数据并给出下一个项目不存在的错误或只是从0循环项目。如何停止获取数据数据库的最后一项?这是我的代码:

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}
        />
      );
  }
}
}

1 个答案:

答案 0 :(得分:0)

请注意没有留下任何物品

将状态更改为

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

让抓取更像这样

_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,
      });
    });
  }

向onEndReached添加逻辑

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