仅加载Flatlist中的可见图像本地响应

时间:2017-11-10 08:56:46

标签: react-native react-native-android react-native-flatlist

我使用Flatlist创建了一个图像网格。我正在从网上加载图像。目前,只要我导航到该特定页面,就会加载所有图像。我想要的只是加载那些在屏幕上可见并停留在滚动上的图像。屏幕上一次显示六个图像。

是否可以在Flatlist的滚动条上加载图像?

3 个答案:

答案 0 :(得分:3)

您需要合并的属性实际上是initialNumToRenderwindowSize。如果您只想要一次显示一个图像屏幕,则可以使用windowSize={1}。我个人建议你至少使用windowSize = {3},这样你就可以使用上一个和下一个屏幕渲染,这实际上取决于你所显示的图像的大小。 另请注意,永远不会删除使用initialNumToRender指定的项目。这是为了允许"转到顶部"功能。您可能想要也可能不想要这些物品。

还可以注意到,您可能需要对这些图像实施某种缓存。一旦你'放弃'"他们需要再次渲染它们,为它们提出新的请求,从而在用户的设备上使用更多的带宽。

答案 1 :(得分:1)

您应该可以使用平面列表中的initialNumToRender属性执行此操作。

所以你的flatList声明可能是:

<FlatList
    initialNumToRender={2}
    data={[{key: 'a'}, {key: 'b'}]}
    renderItem={({item}) => <Text>{item.key}</Text>}
/>

答案 2 :(得分:1)

您可以如下使用Flatlist来仅加载当前视口中的那些图像。

             <FlatList
                    ref={(view) => (this.parentScrollView = view)}
                    data={this.state.data}
                    onScroll={this.handleScroll}
                    keyExtractor={keyExtractor}
                    showsVerticalScrollIndicator={false}
                    bounces={false}
                    numColumns={3}
                    renderItem={this.renderItem}
                    ItemSeparatorComponent={this.ItemSeparatorComponent}
                    ListEmptyComponent={this.ListEmptyComponent}

                    //code for optimization and load only visible items
                    initialNumToRender={8}
                    maxToRenderPerBatch={2}
                    onEndReachedThreshold={0.1}
                    onMomentumScrollBegin={this.onMomentumScrollBegin}
                    onEndReached={this.onEndReached}
           />

我的onEndReached是:

onEndReached = () => {
        console.log('end reached');
        if (!this.onEndReachedCalledDuringMomentum) {
            console.log('loading more archived products');
            this.loadMoreProducts();                
            this.onEndReachedCalledDuringMomentum = true;
        }
    }

onMomentumScrollBegin是:

onMomentumScrollBegin = () => { this.onEndReachedCalledDuringMomentum = false; }

initialNumToRender将装载前8个项目,除非Flatlist本身未卸载,否则将永远不会将其删除。在快速滚动列表的同时保持列表滚动性能很有帮助。

onMomentumScrollBeginonEndReachedThreshold用于何时为列表加载更多元素。这可能是API调用等。