如何高性能渲染长列表?
在工作中, 可能会有遇到一些不能使用懒加载/分页查询的方式来进行列表的加载. 比如我们的功能机中的某个通话记录的列表, 类似这种, 需要实时查看列表而不是分页或者延时懒加载的, 我们称之为长列表.
问题: 怎样高性能渲染此类型的长列表?
由于数据量较大, 一次性渲染全部数据的话, 在性能较差的终端设备上, 就会比较卡顿.
思路:
-
构建一个固定长度的虚拟列表
-
监听滚动事件
-
动态替换列表中的元素
如何不引入第三方库的前提下, 实现虚拟列表渲染的组件:
- 这里以React项目为例:
- 元素固定高度 - 简易代码 :
import React, { Component } from 'react';
// Maximum displayable number of visible area
// x = Math.ceil(screenHeight / itemHeight)
const MAX_ITEMS_SHOW = x;
// Fixed length of virtual rendering list (number of actual renderings)
const MAX_ITEMS_RENDER = y;
class VirtualList extends Component {
constructor(props) {
super(props);
this.state = {
index: 0
};
}
scroll(dir = 'up') {
const { items } = this.props;
let { index } = this.state;
if (dir === 'up' && index > 0) {
index -= 1;
}
if (dir === 'down' && index < items.length - MAX_ITEMS_SHOW) {
index += 1;
}
this.setState({ index });
}
itemsToRender = () => {
const { items } = this.props;
const { index } = this.state;
return items.slice(index, index + MAX_ITEMS_RENDER);
}
render() {
const { className } = this.props;
return (
<div className={className}>
{itemsToRender}
</div>
);
}
}
export default VirtualList;
- 元素动态高度 - 代码 :
import React, { Component } from 'react';
class VirtualList extends Component {
constructor(props) {
super(props);
this.state = {
visibleList: []
};
this.wholeList = [];
// x: scroll step(rem)
this.SCROLL_STEP = x;
this.currentScrollPosition = 0;
this.visibleListCount = 5;
this.startOffset = 0;
}
componentDidMount() {
window.onkeydown = this.onKeyDown.bind(this);
}
componentDidUpdate(prevProps) {
const { isFetched, wholeList, positions } = this.props;
// First time update, set the whole to this.wholeList.
// If use hooks-> useEffect(), no need `isFetched`.
if (isFetched && !prevProps.isFetched) {
this.wholeList = wholeList;
this.positions = positions;
this.setVisibleList();
// Use `querySelector` to get scollList instead of `this.ref` in render,
// fetch whole list maybe async, if in render, refer will be triggered repeatedly.
this.scrollList = document.querySelector('.virtual-list-wrapper');
}
}
// Current stage: only support up/down sroll.
// Key down evt.
onKeyDown(evt) {
evt.preventDefault();
evt.stopPropagation();
this.scroll(evt.key);
}
getStartIndex(list, value) {
// In order to reduce the search times about start index of visible list,
// need a binary search here.
let start = 0;
let end = list.length - 1;
let tempIndex = 0;
while (start <= end) {
const midIndex = parseInt((start + end) / 2, 10);
const midValue = list[midIndex];
if (midValue === value) {
return midIndex + 1;
}
if (midValue < value) {
start = midIndex + 1;
} else if (midValue > value) {
if (tempIndex === 0 || tempIndex > midIndex) {
tempIndex = midIndex;
}
end -= 1;
}
}
return tempIndex;
}
setVisibleList(startIndex = 0) {
const endIndex = Math.min(
startIndex + this.visibleListCount,
this.wholeList.length
);
this.setState({
visibleList: this.wholeList.slice(startIndex, endIndex)
});
}
scrollVisibleList() {
const { listHeight } = this.props;
// If the client window can display the whole data completely,
// there is no need to scroll.
const isNeedScroll = listHeight > this.scrollList.clientHeight;
if (!isNeedScroll) {
this.startOffset = 0;
return;
}
const startIndex = this.getStartIndex(
this.positions,
currentScrollPosition
);
// current startOffset item's height
const currentStartItemSize =
0 === startIndex
? this.positions[startIndex]
: this.positions[startIndex] - this.positions[startIndex - 1];
this.startOffset =
currentScrollPosition -
(currentScrollPosition % currentStartItemSize);
this.setVisibleList(startIndex);
}
scroll(dir = 'up') {
const { scrollHeight, clientHeight } = this.scrollList;
if (dir === 'up' && this.currentScrollPosition > 0) {
this.currentScrollPosition -= this.SCROLL_STEP;
}
// When scroll to the bottom, no need to set offset any more.
if (dir === 'down' && scrollHeight > 0 && this.currentScrollPosition + clientHeight <= scrollHeight) {
this.currentScrollPosition += this.SCROLL_STEP;
}
this.scrollList.scrollTop = this.currentScrollPosition;
this.scrollVisibleList();
}
render() {
const { listHeight } = this.props;
const { visibleList } = this.state;
return (
<div className='virtual-list-wrapper'>
<div className='phantom-list' style={{ height: `${listHeight}rem` }} />
<div
className='render-list'
style={{ transform: `translate3d(0, ${this.startOffset}rem, 0)` }}
>
{visibleList}
</div>
</div>
);
}
}
export default VirtualList;
React官方推荐了使用React-window, 来做虚拟列表渲染
注: 但是对于一些对代码体积大小非常敏感的移动端项目来说, 引入该库会增加大概十几kb, 这种应用场景下, 我们可以自己手动写一个符合需求的组件.