如何为scrollView添加ActivityIndi​​cator?

时间:2019-01-29 12:54:15

标签: javascript reactjs react-native

我正在尝试在ScrollView中添加ActivityIndi​​cator以显示20个项目。加载后将显示更多20个项目。

在下面的代码中,ActivityIndi​​cator显示在scrollView的末尾,但我需要在20个项目后使用它。

import React, { Component } from 'react';
import { View, ScrollView, Alert, ActivityIndicator } from 'react-native';
import AlbumDetail from './AlbumDetail';
import axios from 'axios';

class AlbumList extends Component {
state = {
    isLoading: false,
    albums: [],
};
componentWillMount() {
    axios
     .get('http://www.json-generator.com/api/json/get/cqgdfqryzS?indent=2')
    .then(response => this.setState({ albums: response.data }));
}
componentDidMount() {
    {this.setState({ isLoading: false })}
}

renderAlbums() {
    return this.state.albums.map(album => (
    <AlbumDetail key={album.name} album={album} />
    ));
}
render() {
    return (
    <ScrollView>
        {this.renderAlbums()}
        <ActivityIndicator size="large" color="#0000ff" />
    </ScrollView>
    );
}
}

export default AlbumList;

1 个答案:

答案 0 :(得分:0)

正如我所见,一旦用户滚动到最后,您需要显示加载。为此,FlatList似乎是ScrollView之外最好的组件。当列表滚动到最后时,ListFooterComponent道具将自动被调用。因此,重构代码如下:

import React, { Component } from 'react';
import { View, FlatList, Alert, ActivityIndicator } from 'react-native';
import AlbumDetail from './AlbumDetail';
import axios from 'axios';

class AlbumList extends Component {
state = {
    isLoading: false,
    albums: [],
};
componentWillMount() {
    axios
     .get('http://www.json-generator.com/api/json/get/cqgdfqryzS?indent=2')
    .then(response => this.setState({ albums: response.data }));
}
componentDidMount() {
    {this.setState({ isLoading: false })}
}

Render_Footer=()=>{
  return (
    <ActivityIndicator size="large" color="#0000ff" />
  )        
}

render() {
    return (
   <FlatList
            keyExtractor = {( item, index ) => index }
            data = { this.state.albums}      
            renderItem = {({ item }) => <AlbumDetail key={item.name} album={item } />}
            ListFooterComponent = { this.Render_Footer }
          />
    );
}
}

export default AlbumList;