英文:
react-lazy-load-image-component is not working as expected
问题
I'm trying to lazy load images using react-lazy-load-image-component. But it is making all the images load at once.
Here's how it looks in the network tab
Here's my code:
import { useState, useEffect } from 'react';
import { LazyLoadImage } from 'react-lazy-load-image-component';
import 'react-lazy-load-image-component/src/effects/blur.css';
function App() {
const [images, setImages] = useState([]);
const url = "https://api.unsplash.com/photos/?client_id=9MRdzVycZVHXD5HX93lbynQl8ZCj3_rrV5LSJSuEp4o&query=nature&per_page=30";
useEffect(() => {
fetch(url)
.then(res => res.json())
.then(data => setImages(data))
}, [])
return (
<>
<div style={{display: "grid", gridTemplateColumns: "repeat(4, 1fr)"}}>
{
images.map(image => (
<LazyLoadImage
loading='lazy'
effect='blur'
src={image.urls.regular}
alt={image.alt_description} key={image.id}
width="100%" />
))
}
</div>
</>
)
}
export default App
(Note: I've provided the translated code, as requested, without additional content.)
英文:
I'm trying to lazy load images using react-lazy-load-image-component. But it is making all the images load at once.
Here's how it looks in the network tab
Here's my code
import { useState, useEffect } from 'react'
import { LazyLoadImage } from 'react-lazy-load-image-component';
import 'react-lazy-load-image-component/src/effects/blur.css';
function App() {
const [images, setImages] = useState([]);
const url = "https://api.unsplash.com/photos/?client_id=9MRdzVycZVHXD5HX93lbynQl8ZCj3_rrV5LSJSuEp4o&query=nature&per_page=30";
useEffect(() => {
fetch(url)
.then(res => res.json())
.then(data => setImages(data))
}, [])
return (
<>
<div style={{display: "grid", gridTemplateColumns: "repeat(4, 1fr)"}}>
{
images.map(image => (
<LazyLoadImage
loading='lazy'
effect='blur'
src={image.urls.regular}
alt={image.alt_description} key={image.id}
width="100%" />
))
}
</div>
</>
)
}
export default App
答案1
得分: 1
你需要确保为你的图片设置高度和宽度属性或占位符,这应该有助于解决问题,因为所有的图片在加载时都是0 x 0大小,将它们全部显示然后一次性加载它们会有所帮助。
英文:
You need to make sure you either set height and width props or a placeholder to your images, that should help with the problem, since all the images are size 0 x 0 when loading, making all visible and then load them all at once.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论