【问题标题】:FlatList - loops items when fetching more with no items left - React NativeFlatList - 在没有剩余项目的情况下获取更多项目时循环项目 - React Native
【发布时间】:2017-11-03 21:35:05
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

    只需制作参数以通知没有剩余物品

    改变状态

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

    让 fetch 更像这样

    _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())
                    }
                }
            }
    

    【讨论】:

    • 这一行给我一个错误:if (!this.state.isLastData)
    • 您是否将 isLastData 添加到您的状态?你能改变服务器数据响应吗?如果没有,我会为你更新代码
    • 我确实将它添加到我的状态。很遗憾,我无法更改服务器数据响应。
    • 我不知道如何检查最后一项
    • 最后的数据响应是什么?响应子级是空的吗?
    猜你喜欢
    • 2019-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-10
    • 1970-01-01
    • 2018-04-01
    相关资源
    最近更新 更多