现在有一个虚拟列表list
,每次加载新的元素时,会先只保留旧list里面的倒数前5个,然后再把新的元素加进来.
也就是说list.length
始终等于5 + n
,其中n
是每次新添加进list
的元素,且n<=5
.
但是这样做会导致 新添加的元素被渲染出来时整体向上移动
这个有办法解决吗?
virtualList
组件
react-infinite-scroll-component
代码
虚拟列表本身
<InfiniteScroll
next={onScrollAction}
hasMore={tmpClaimList.length < claimList.length}
loader={<p style={{ textAlign: 'center' }}>Loading...</p>}
dataLength={tmpClaimList.length}
ref={listRef}
scrollThreshold="200px"
>
{renderClaimList.map((param, index: number) => (
<div key={index} style={{ margin: '1rem 1.5rem' }}>
{/* 一些动态高度的Item */}
</div>
))}
</InfiniteScroll>
onScrollAction
const [tmpClaimList, setTmpCliamList] = useState()
const [renderClaimList, setRenderCliamList] = useState()
const claimList = Array.from(claimMap)
useEffect(() => {
if (tmpClaimList.length > 20) {
setRenderCliamList(tmpClaimList.slice(-10))
} else {
setRenderCliamList(tmpClaimList)
}
}, [tmpClaimList])
const onScrollAction = () => {
setTimeout(() => {
Array.from({ length: 3 }).forEach((item: any, index: number) => {
const curIdx = tmpClaimList.length + index
if (curIdx >= claimList.length) return
tmpClaimList.push(claimList[tmpClaimList.length + index])
})
setTmpCliamList([...tmpClaimList])
}, 500)
}