虚拟列表
在工作中,我们经常会以列表的形式来展示内容,当时如果列表项很多的话,在pc端我们会考虑用分页的形式来解决长列表带来的性能问题。但是如果是在移动设备,为了用户体验,我们通常是用长列表的形式来展示,用户只需上下滑动来浏览。这时如果不做处理,而是一次加载全部的数据,那么当数据量过大的时候,就会出现性能问题,影响体验。这时,我们就需要用到*虚拟列表*
了。
虚拟列表是按需显示的一种技术,可以根据用户的滚动,不必渲染所有列表项,而只是渲染可视区域内的一部分列表元素的技术。
如图所示,当页面有很多数据的时候,我们只需渲染用户可看到的区域item8
到item15
。这样就大大提升了性能和用户体验。
固定高度长列表
我们项目中的列表如果都是高度固定,那么这种情况就是固定高度的长列表。这种情况的处理相对简单,我们只要根据可视区域的高度和列表的高度,就能计算出可视区域要渲染列表项的索引(范围)啦。
首先我们可以根据scrollTop
属性来确定可视区域开始项的索引;然后我们可以根据可视区域的高度和列表项的高度,计算得出结束索引的值,这样可视区域要渲染的内容索引已经确认,可视区域上下方的高度,也就是开始索引的值列表项的高度和(列表的长度-结束索引)列表项的高度。监听容器的scroll
事情,重复上面的计算,这就是当列表项目固定的情况下,实现虚拟列表的原理。
如果是列表项高度不一,但是我们可以确定没项列表的高度,那么也是可用上面的方法计算,我们只需为列表增加一个height
属性来记录每个列表的高度,然后根据索引和之前列表的高度相加,我们就可以确定当前列表的top
相对与股东容器的高度,这样形成了一个有序的top值数组,然后我们就可以使用二分法
结合固定列表项高度
的情况来得到可视区域的索引范围。
由于本文的讨论重点不是上面两种情况,对上面两种情况感兴趣的同学,推荐我自己之前看到过的一篇文章,讲的很详细 虚拟滚动的轮子是如何造成的?
不固定列表高度的情况
终于来到今天讨论的重点啦。在高度不固定的情况下,要怎么实现虚拟列表呢?通过前面的概述,相信大家也认识到要实现一个虚拟列表,我们只需要确定可是区域的渲染范围(索引)即可,滚动盒子上下高度根据计算出来的索引和列表的总长度就可以计算出来啦。那么,我们要怎么确定可视区域要渲染列表的索引呢?
其实在高度不确定的情况下,我们就只有等到列表项渲染完成后,才能得到列表项的真实高度,所以我们要动态的记录列表项的真实高度。为了不是页面发生错误的情况,我们需要一个预估列表项的高度来尽可能撑开滚动盒子,就等到列表项渲染后,我们就可以拿到真实dom的高度,在替换可视区域。考虑到单独的记录每个列表项的真实高度,会比较麻烦,所以我就页为单位来记录pageHeight
。
来看代码ScrollList
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190import React, { PureComponent } from 'react'
import { throttle } from '../../utils/index'
// 应该接收的props: renderItem: Function, height:string; estimateHeight:Number
class ScrollList extends PureComponent {
constructor (props) {
super(props)
this.renderItem = props.renderItem
this.getData = props.getData
// 预估高度 做屏幕适配
this.estimateHeight = document.documentElement.clientWidth * (props.estimateHeight / 320)
// 每一页展示的数据
//一页10条数据,进行一页数据的预估
// 每一页的总体高度
this.pageHeight = []
this.state = {
List: []
}
this.scrollWrapper = React.createRef()
this.handleScroll = throttle(this.onScroll, 300)
this.hasDidMounted = false
}
async componentDidMount () {
console.log('----- sroll list mount')
this.init()
this.hasDidMounted = true
}
init=async (isEimtByParant = false) => {
const { offset, events } = await this.props.getData()
this.initOptions({ offset, events, isEimtByParant })
}
// resource
// static getDerivedStateFromProps ({ resource, pageSize }) {
// if (resource.length && resource.length <= pageSize) {
// self.initOptions({ offset: 0, events: resource })
// console.log(resource, pageSize)
// }
// return null
// }
initOptions = ({ offset = 0, events = [], isEimtByParant }) => {
const page = Math.floor(offset / this.props.pageSize)
let pageList = [...this.state.List]
if (!offset) {
pageList = []
}
// 列表数据
if (!pageList.length) {
pageList[0] = {
data: events,
visible: true
}
} else {
pageList[page] = {
data: events,
visible: false
}
}
if (isEimtByParant) {
this.pageHeight = []
}
// debugger
// 然后对pageHeight根据预估高度进行预估初始化,后续重新进行计算,每个列表的预估位置高度
if (this.pageHeight.length) {
this.pageHeight[page] = {
top: this.pageHeight[page - 1].height + this.pageHeight[page - 1].top,
height: this.estimateHeight * events.length,
isComputed: false
}
} else {
this.pageHeight.push({
top: 0,
height: this.estimateHeight * events.length,
isComputed: false
})
}
console.log('inint options ', this.pageHeight)
this.setState({
List: pageList
})
}
initHeight =(offsetHeight, scrollTop) => {
requestAnimationFrame(() => {
// 判断一下需要展示的列表,其他的列表都给隐藏了
const listShow = [...this.state.List]
// console.log(listShow)
listShow.forEach((item, index) => {
if (this.pageHeight[index]) {
const bottom = this.pageHeight[index].top + this.pageHeight[index].height
// console.log('------', bottom, scrollTop, this.pageHeight[index].top > scrollTop + offsetHeight + 5)
if ((bottom < scrollTop - 10) || (this.pageHeight[index].top > scrollTop + offsetHeight + 10)) {
listShow[index].visible = false
} else {
// 根据预估高度算出来它在视野内的时候,先给它变成visible,让他出现,才能拿到元素高度
this.setState(prevState => {
const List = [...prevState.List]
List[index].visible = true
return {
List
}
})
// console.log(1111111, this.state.List)
// 出现以后,然后计算高度,替换掉之前用预估高度设置的height
const target = this[`page${index}`].current
let top = 0
if (index > 0) {
top = this.pageHeight[index - 1].top + this.pageHeight[index - 1].height
}
if (target && target.offsetHeight && !listShow[index].isComputed) {
this.pageHeight[index] = { top, height: target.offsetHeight }
// console.log(target.offsetHeight)
listShow[index].visible = true
listShow[index].isComputed = true
// 计算好了以后,还要再setState一下,调整列表高度
this.setState({
List: listShow
})
}
}
} else {
this.pageHeight[index] = { top, height: this.estimateHeight * this.props.pageSize }
}
})
})
}
onScroll= async () => {
const { offsetHeight, scrollHeight, scrollTop } = this.scrollWrapper.current
this.initHeight(offsetHeight, scrollTop)
// console.log(offsetHeight, scrollHeight)
if (offsetHeight + scrollTop + 10 > scrollHeight && this.props.hasMore) {
const { events, offset } = await this.props.getData(1)
this.initOptions({ offset, events })
this.initHeight(offsetHeight, scrollTop)
}
}
render () {
const { List } = this.state
// console.log('list', List)
let headerHeight = 0
let bottomHeight = 0
let i = 0
for (; i < List.length; i++) {
if (!List[i].visible) {
headerHeight += this.pageHeight[i].height
} else {
break
}
}
for (; i < List.length; i++) {
if (!List[i].visible) {
bottomHeight += this.pageHeight[i].height || 0
}
}
const renderList = List.map((item, index) => {
this[`page${index}`] = React.createRef()
if (item.visible) {
return <div ref={this[`page${index}`]} key={`${item.id}_page${index}`}>
{item.data.map((value, log) => {
return (
this.renderItem(value, `${index}-${log}`)
)
})}
</div>
}
})
return (<div
ref={this.scrollWrapper}
onScroll={this.handleScroll}
style={{ height: '100%', overflow: 'scroll' }}
>
<div style={{ height: headerHeight }} />
{renderList}
<div style={{ height: bottomHeight }} />
{/* {this.state.loading && (
<div>加载中</div>
)}
{this.state.showMsg && (
<div>暂无更多内容</div>
)} */}
</div>)
}
}
export default ScrollList
从代码中我们可以看到组件ScollList
接收的props有:
- renderItem:渲染列表项的函数,由用户传入即可。
- hasMore:判断是否还有下一页数据,用户往下滑动。
- pageSize:表示每一页的列表项,因为scrollList是以页为单位来计算高度的
- getData: 获取列表项
- estimateHeight: 列表项的预估高度,可以稍微大些,撑开滚动盒子的高度
原理梳理
- 先设置一个预设一个列表高度,如 320
然后componentDidMounted中加载一页数据,并用
pageHeight
来存储每一页(10)条数据的预估高度和,还有顶端位置,用top
记录1
2
3
4
5
6
7// pageHeight
[
{
top: 0,
height: document.documentElement.clientWidth * (props.estimateHeight / 320)
}
]在state中用List,来接受请求的数据
1
2
3
4
5
6
7[
{
data: [....] // 要渲染的真实数据,
isComputed: false // 表示这页数据是用的预估的高度来渲染的,在滚动事件中,我们会用真实的这页数据的高度来替换,在重新更新页面
visible: false // 标示本页数据是否在可是区域
}
]scroll事件,根据hasMore来请求后面的数据
最后贴下冴羽大佬的throttle
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38export const throttle = (func, wait, options = { leading: true, trailing: true }) => {
let timeout, context, args // result
let previous = 0
if (!options) options = {}
const later = function () {
previous = options.leading === false ? 0 : new Date().getTime()
timeout = null
func.apply(context, args)
if (!timeout) context = args = null
}
const throttled = function () {
const now = new Date().getTime()
if (!previous && options.leading === false) previous = now
const remaining = wait - (now - previous)
context = this
args = arguments
if (remaining <= 0 || remaining > wait) {
if (timeout) {
clearTimeout(timeout)
timeout = null
}
previous = now
func.apply(context, args)
if (!timeout) context = args = null
} else if (!timeout && options.trailing !== false) {
timeout = setTimeout(later, remaining)
}
}
throttled.cancel = () => {
clearTimeout(timeout)
previous = 0
timeout = null
}
return throttled
}
小结
以上就是本人在项目有用到的虚拟列表实现方法,大家可以帮忙优化下哈!