首页 > 解决方案 > 大型组件作为 VirtualizedList/etc 中的部分?

问题描述

如果我想在虚拟化列表中显示一堆异构数据,默认的做法似乎是让父组件收集所有数据,以便它可以创建提供给列表组件的部分。

有没有办法避免要求父组件这样做?我想将父组件与数据收集部分分离,这样它所要做的就是声明它具有这样那样的组件,然后这些组件将负责收集数据。

如果它是 ScrollView,这将非常简单:

<ScrollView>
    <SectionA>
    <SectionB>
    <SectionC>
</ScrollView>

但是,为了利用 VirtualizedList 的性能增益,如果每个部分都很大,我需要将每个部分的单独数据传递到 VirtualizedList。我不确定如何执行此操作或是否可能。

标签: react-nativereact-native-flatlistreact-virtualizedreact-native-sectionlist

解决方案


不确定这是惯用的还是粗俗的 React 反模式,但我解决它的方法是将每个部分实现为纯无头数据Component

export type SectionDataComponentProps = {
  onDataChanged?: () => void, // call this whenever the data updates.
}

export class SectionDataComponent<P : SectionDataComponentProps, S, ItemT> extends React.PureComponent<P, S> {

  // Implemented by subclasses
  getSectionData() : Array<SectionT<ItemT>> { 
      // returns an array of sections for a SectionList...
  }
  render() {
    // business logic component only.
    return null;
  }
}

父组件通过使用 来跟踪它们ref,然后根据需要调用 getSectionData()。


推荐阅读