我想一次渲染一个视频缩略图,以便提高网站的性能。
我尝试使用 map ,但 map 一次循环遍历所有项目并返回要渲染的组件列表
我也尝试过使用 while 循环,但 while 循环仅渲染一个缩略图(第一个缩略图)
这是我的渲染方法
render(){
const { videos } = this.state;
const listVideos = () => {
let vids = videos
let loopedAllVids = false;
while(!loopedAllVids){
const head = R.head(vids); // returns first item
const { thumbnail } = head;
vids = R.tail(vids); // returns all items but first item
if(vids.length === 0){
loopedAllVids = true;
}
return(
<div
className='video'
style={{background:`url(${thumbnail})`}}>
</div>
)
}
}
return(
<div className="row text-center">
<div className="col-md-12 header">
<h1> My Youtube Videos </h1>
</div>
<div className="col-md-12">
<div className="row">
<div className="col-md-8 col-xs-12 col-md-offset-2 videos">
{videos.length> 0 && listVideos()}
</div>
</div>
</div>
</div>
)
}
最佳答案
while 方法仅返回一个拇指,因为“return”语句停止 while 循环,而 map 方法在迭代第一个数组后返回一个新数组。
无论如何,我认为这不是实现您目标的正确方法。 我认为最好将您的拇指存储在组件状态中,并将其一个一个地递增(也许使用“setTimeout”方法)。
另一种方法是查看现有的“Lazyload”解决方案(例如 https://github.com/twobin/react-lazyload)。
关于javascript - 如何在 react 中一项一项地渲染列表中的项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55759612/