簡體   English   中英

React Native:你的列表很大,更新很慢

[英]React Native: You have a large list that is slow to update

我正在嘗試使用 FlatList 在 React Native 中實現分頁。 我遵循了最佳實踐,但我仍然收到以下錯誤:

VirtualizedList:您有一個更新緩慢的大型列表 - 確保您的 renderItem function 呈現遵循 React 性能最佳實踐(如 PureComponent、shouldComponentUpdate 等)的組件。Object {“contentLength”:23651.73242918,“prevdt7” : 865, }

這是代碼:

const NewsScreen = ({ isLoading, news, fetchInitialNews, fetchMoreNews, isLoadingMore, hasMoreToFetch }) => {
 
  useEffect(() => {
    fetchInitialNews();
  }, []);

  const onEndReached = () => {
    fetchMoreNews();
  };

  return (
      <NewsList
        isLoading={isLoading}
        news={news}
        numSkeletonsToShow={LATEST_NEWS_CONSTANTS.NUM_TO_SHOW}
        contentContainerStyle={STYLES.newsListContentContainer}
        onEndReached={onEndReached}
        isLoadingMore={isLoadingMore}
        hasMoreToFetch={hasMoreToFetch}
      />
  );
};
const renderNewsItem = ({ item, index }) => (
  <NewsItem news={item} containerStyle={index !== 0 ? GLOBAL_STYLES.cardMargin : null} />
);

const NewsList = ({
  isLoading,
  news = [],
  isLoadingMore,
  contentContainerStyle = {},
  onEndReached,
  hasMoreToFetch
}) => {
  const dummySkeletonArray = Array(numSkeletonsToShow).fill("1");

  const onScrollToEnd = () => {
    if (!isLoadingMore && hasMoreToFetch) {
      onEndReached();
    }
  };

  if (isLoading) {
    return (
      //..loading indicator
    );
  }

  return (
    <FlatList
      data={news}
      keyExtractor={(n) => n.url}
      renderItem={renderNewsItem}
      showsVerticalScrollIndicator={false}
      style={GLOBAL_STYLES.flatListContentContainer}
      contentContainerStyle={contentContainerStyle}
      onEndReached={onScrollToEnd}
      onEndReachedThreshold={0.2}
      ListFooterComponent={hasMoreToFetch && <ActivityIndicator animating={isLoadingMore} />}
    />
  );
};
const areEqual = () => true;

const NewsItem = ({ news, containerStyle }) => {
  return (
    <TouchableNativeFeedback viewContainerStyle={containerStyle}>
      <Card>
      </Card>
    </TouchableNativeFeedback>
  );
};

export default memo(NewsItem, areEqual);

正如許多其他帖子所建議的那樣,我使用了memo並將renderItem移到了功能組件之外。 仍然沒有運氣。 謝謝您的幫助!

就我而言,這是因為OnEndReached被多次調用。 由於您正在嘗試從服務器獲取下一組數據,因此如果在單個 go 中多次調用 onEndReached,它會嘗試多次從服務器調用。 我通過使用 state 來避免多次調用來解決:

const [loader, setLoader] = useState(false);

const onEndReached = (page) => {
  if (!loader) {
    setPage(page + 1)
  }
}

const loadData = async () => {
  setLoader(true);
  const resp = await fetchMoreNews();
  setLoader(false);
}

<FlatList ...someprops onEndReached={onEndReached} />

在其他一些情況下,將以下代碼添加到您的 Flatlist 也可以,其中 n 是一個小數字(在我的情況下為 10)。

initialNumToRender={n} 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM