城市列表(五)01-长列表缓存组件使用——react-virtualized组件-提升列表加载性能 & Array.from()-新数组 & Array map()-新数组
-
官网:https://bvaughn.github.io/react-virtualized/#/components/List
http://www.reactvirtualized.com
yarn add react-virtualized
import 'react-virtualized/styles.css'
import { List } from 'react-virtualized'
const list = Array.from(new Array(1000)).map(
(item, index) => `第${index}行数据`
)
function rowRenderer({
key, // Unique key within array of rows
index, // Index of row within collection
isScrolling, // The List is currently being scrolled
isVisible, // This row is visible within the List (eg it is not an overscanned row)
style // Style object to be applied to row (to position it)
}) {
return (
<div key={key} style={style}>
{list[index]}
</div>
)
}
<List
width={300}
height={300}
rowCount={list.length}
rowHeight={100}
rowRenderer={rowRenderer}
/>
实例
第一步:打开react-virtualized官网,查看示例
第二步:安包
yarn add react-virtualized
第三步:所在界面src/views/City/index.js进行引入
import { List, AutoSizer } from 'react-virtualized'
第四步:index.js中操作界面
结构
{/*{this.renderCityList()}*/}
{/*
width和height:列表的宽度和高度
rowCount:列表的长度
rowHeight:行的高度
rowRenderer:渲染每一个条目的模板
*/}
<List
width={300}
height={300}
rowCount={list.length}
rowHeight={20}
rowRenderer={this.rowRenderer}
/>
模板
// 用于产生每一行的模板
rowRenderer = ({
// key每一个条目的唯一标识
key,
// 每一个条目的样式
style,
// 当前条目的索引
index
}) => {
// 渲染每一个条目的模板
<div key={key} style={style}>
{list[index]}
</div>
)
}
模拟假数据
// 列表假数据——列表缓存模拟使用
// ['第0行数据', '第1行数据',......]
const list = Array.from(new Array(50)).map(
(item, index) => `第${index}行数据`
)
列表加载效果
内在逻辑-为列表熏染预加载出一部分