Skip to content

Commit d4e91c4

Browse files
authored
feat(image): ssr 适配 (jdf2e#1579)
1 parent d015ebc commit d4e91c4

File tree

1 file changed

+26
-14
lines changed

1 file changed

+26
-14
lines changed

src/packages/image/image.tsx

Lines changed: 26 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -77,33 +77,45 @@ export const Image: FunctionComponent<
7777
onLoad,
7878
onError,
7979
} = { ...defaultProps, ...props }
80-
const [innerLoading, setInnerLoading] = useState(true)
80+
const [innerLoading, setInnerLoading] = useState(false)
8181
const [isError, setIsError] = useState(false)
82+
const [complete, setComplete] = useState(false)
8283
const imgRef = useRef<HTMLImageElement>(null)
8384

8485
useEffect(() => {
85-
if (
86-
imgRef.current &&
87-
imgRef.current.complete &&
88-
imgRef.current.naturalHeight !== 0
89-
) {
90-
setInnerLoading(false)
91-
} else if (src) {
86+
if (imgRef.current && imgRef.current.complete) {
87+
if (imgRef.current.naturalHeight === 0) {
88+
handleError()
89+
} else {
90+
handleLoad()
91+
}
92+
} else {
93+
// 非 SSR 模式下开启 loading
9294
setInnerLoading(true)
9395
}
96+
}, [imgRef])
97+
98+
useEffect(() => {
99+
setComplete(false)
94100
}, [src])
95101

96102
// 图片加载
97103
const handleLoad = () => {
98-
setIsError(false)
99-
setInnerLoading(false)
100-
onLoad && onLoad()
104+
if (!complete) {
105+
setIsError(false)
106+
setInnerLoading(false)
107+
onLoad && onLoad()
108+
setComplete(true)
109+
}
101110
}
102111
// 图片加载失败
103112
const handleError = () => {
104-
setIsError(true)
105-
setInnerLoading(false)
106-
onError && onError()
113+
if (!complete) {
114+
setIsError(true)
115+
setInnerLoading(false)
116+
onError && onError()
117+
setComplete(true)
118+
}
107119
}
108120

109121
const containerStyle = {

0 commit comments

Comments
 (0)