首页 > 解决方案 > 有没有办法限制在调用 URL 的响应中返回的 Web 数据量?

问题描述

有没有办法限制在调用 URL 的响应中返回的 Web 数据量?

或者有没有办法让它在滚动加载的组件时刷新以获取更多数据?

let { url, timeout } = urlConfig.getStuffc; url = `${url}?${constructQueryFromArr(statusQueryString[status], 'status')}`; httpRequest('get', url, { config: { timeout } }).then((response) => { dispatch(showSpinner(false)); } //do something

标签: react-native

解决方案


这是在单个请求中使用有限数据Flatlist实现的基本示例API

export default class App extends Component {

  constructor(props) {
    super(props);
    this.page = 1;
    this.state = {
      loading: false, // user list loading
      isRefreshing: false, //for pull to refresh
      data: [], //user list
      error: ''
    }
  }

  componentWillMount() {
    this.fetchUser(this.page) //Method for API call
  }

  fetchUser(page) {
    const url = `https://api.example.com?page=${page}`;
    this.setState({ loading: true })
    axios.get(url)
      .then(res => {
        let listData = this.state.data;
        let data = listData.concat(res.data.items) . //concate list with response
        this.setState({ loading: false, data: data })
      })
      .catch(error => {
        this.setState({ loading: false, error: 'Something just went wrong' })
      });
  }

  handleLoadMore = () => {
    if (!this.state.loading) {
      this.page = this.page + 1; // increase page by 1
      this.fetchUser(this.page); // method for API call 
    }
  };

  render() {
    if (this.state.loading && this.page === 1) {
      return <View style={{
        width: '100%',
        height: '100%'
      }}><ActivityIndicator style={{ color: '#000' }} /></View>;
    }
    return (
      <View style={{ width: '100%', height: '100%' }}>
        <FlatList
          data={this.state.data}
          extraData={this.state}
          renderItem={({ item }) => (
            <View>
            ....
            </View>
          )}
          keyExtractor={(item, index) => index.toString()}
          onEndReachedThreshold={0.4}
          onEndReached={this.handleLoadMore.bind(this)}
        />
      </View>
    );
  }
}

推荐阅读