从ScrollView迁移到FlatList

时间:2020-06-06 08:52:24

标签: react-native

我有很多从服务器获取的项目列表,它可以正常工作,但是问题是我的ScrollView需要很长时间才能呈现项目,在阅读了我本人必须提供“ FlatList”或“ SectionList”而不是ScrollView,如何重构此代码以使用FlatList?

谢谢

import React from 'react';
import {ScrollView, View, Text, Dimensions} from 'react-native';
import ProductItem from 'src/containers/ProductItem';
import {padding} from 'src/components/config/spacing';

const WIDTH_SCREEN = Dimensions.get('window').width;

const Carousel = ({
  data,
  width,
  height,
  widthView,
  col,
  box,
  navigationType
}) => {
  const separator = padding.base;
  const paddingEnd = box ? padding.large: 0;
  const column = col > 0 ? col : 1.5;
  const widthImage = widthView/column;
  const heightImage =(widthImage * height)/width;

  return (
    <ScrollView
      horizontal
      showsHorizontalScrollIndicator={false}
      style={{
        marginHorizontal: -separator/2,
      }}
    >
      {data.map((item, index) => (
        <View
          key={item.id}
          style={{
            marginLeft: separator/2,
            marginRight: index === data.length - 1 ? separator/2 + paddingEnd: separator/2,
          }}
        >
          <ProductItem
            item={item}
            width={widthImage}
            height={heightImage}
            navigationType={navigationType}
          />
        </View>
      ))}
    </ScrollView>
  )
};

Carousel.defaultProps = {
  data: [],
  width: 204,
  height: 257,
  widthView: WIDTH_SCREEN,
  col: 1.5,
  box: false,
};
export default Carousel;

1 个答案:

答案 0 :(得分:0)

您的前端代码对我来说还不错。最好的方法是在后端进行分页,然后以小补丁的形式获取数据。然后,您可以逐段渲染,一次说5个项目。这样可以避免延迟。