Skip to content

Commit 5675b93

Browse files
committed
refactor(react-vite): refactor AppList ref saving logic
1 parent 9cd47b1 commit 5675b93

File tree

1 file changed

+14
-10
lines changed

1 file changed

+14
-10
lines changed

demo/react-vite/src/components/public/AppList.tsx

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import React, { useRef, useEffect } from 'react'
1+
import { useRef, useEffect } from 'react'
22
import type { ReactNode } from 'react'
33
import { NavLink } from 'react-router-dom'
44
import classNames from 'classnames'
@@ -22,35 +22,39 @@ const AppList = ({
2222
className
2323
}: AppListProps) => {
2424
const lazyImageRefs = useRef<Array<HTMLImageElement | null>>([])
25-
const lazyImages = useRef<Array<HTMLImageElement | null>>([])
26-
2725
const initLazyImgLoad = () => {
28-
lazyImages.current = lazyImageRefs.current.map((el) => el)
29-
$_xsl__loadImgLazy(lazyImages.current)
26+
$_xsl__loadImgLazy(lazyImageRefs.current as any)
3027
}
3128
useEffect(() => {
32-
lazyImageRefs.current = lazyImageRefs.current.slice(0, data.length)
3329
initLazyImgLoad()
3430
}, [data, render, className])
3531

3632
useEffect(() => {
3733
initLazyImgLoad()
3834
}, [])
3935

36+
const setLazyImageElement = (
37+
index: number,
38+
element: HTMLImageElement | null
39+
) => {
40+
lazyImageRefs.current[index] = element
41+
return () => {
42+
lazyImageRefs.current.splice(index, 1)
43+
}
44+
}
45+
4046
return (
4147
<ul
4248
className={classNames(styles.AppList, className)}
43-
onScroll={() => $_xsl__loadImgLazy(lazyImages.current)}
49+
onScroll={() => $_xsl__loadImgLazy(lazyImageRefs.current as any)}
4450
>
4551
{data.map((item, index) => {
4652
return (
4753
<li className={classNames(styles.AppList__item, 'main_border_bottom')} key={item.path}>
4854
<NavLink to={item.path} className={styles.AppList__link}>
4955
<img
5056
className={classNames(styles.AppList__img, 'lazyImage')}
51-
ref={(el) => {
52-
lazyImageRefs.current[index] = el
53-
}}
57+
ref={(el) => setLazyImageElement(index, el)}
5458
src={logo__grey}
5559
data-src={item.imgurl}
5660
alt={item.name}

0 commit comments

Comments
 (0)