如何在 Ionic React 中渲染大量项目时减少渲染时间

How to reduce render time while rendering huge list of items in Ionic React

我正在使用 IonicReact 构建移动应用程序。我只想呈现本地 JSON 文件中的项目列表(JSON 文件包含超过 1000 个项目的数组)。我映射数组项并通过将它们包装在 <IonItem> 中来打印它们。迭代所有项并在浏览器中显示它们需要几秒钟。请帮助我,如何优化渲染时间,从 JSON 快速加载数据。 代码如下:

//necessary imports
import data from './data.json';

const ListItems: React.FC = () => {
const showItems = data
.map((topic) => {
return (<IonItem>{topic}</IonItem>);})
 
return (
<IonPage>
<IonContent fullscreen className="bg-style">
<IonList>{showItems}</IonList>
</IonContent>
</IonPage>
);
};
  
export default ListItems; 

基本上应该是两种方法:1.虚拟滚动。 2. 通过将大数组切割成小块来无限滚动。

不过,在你的情况下,虚拟滚动方法应该好得多。

Ionic虚拟卷轴不支持react。但是我找到了一篇文章,重新实现了VirtualScrollChild组件:
https://medium.com/@alvinnguyen116/virtual-and-infinite-scrolling-in-react-d56a05976cd2

import React from "react"
import { useInView } from "react-intersection-observer"

interface Props {
  height?: number
}

export const VirtualScrollChild: React.FC<Props> = (props) => {
  const [ref, inView] = useInView()
  const style = {
    height: `${props.height ? props.height : 40}px`,
    overflow: "hidden",
  }
  return (
    <div style={style} ref={ref}>
      {inView ? props.children : null}
    </div>
  )
}

用法:

    <IonList>
      {your_data_list.map((data) => (
        <VirtualScrollChild height={your_height}>
          {data...}
        </VirtualScrollChild>
      ))}
    </IonList>