一次性大批量的加载资源的时候(比如批量图片的显示),会占用大量的内存,尤其是在一些低内存的设备上会造成卡顿的现象,所以就需要在必要的时候再进行资源的加载。
懒加载就是在真正需要资源才加载资源,这样就可以节省内存,尽可能的减少卡顿现象的出现。
推荐一款懒加载组件:react-lazyload
安装
npm install --save react-lazyload
使用
import React from 'react';
import ReactDOM from 'react-dom';
import LazyLoad from 'react-lazyload';
class Demo extends React.Component {
constructor() {
super();
this.state = {
s_aTC_img: []
}
}
componentDidMount() {
let t_aTC_img = []
for (let i = 1; i < 15; i++) {
t_aTC_img.push({
src: `http://192.168.85.41/static/upload/test/${i}.jpg`,
alt: `${i}.jpg`
})
}
this.setState({ s_aTC_img: t_aTC_img })
}
render() {
return (
<div>
{this.state.s_aTC_img.length ?
this.state.s_aTC_img.map((item, index) => {
return (
<LazyLoad key={index} height={200} >
<img src={item.src} alt={item.alt} width='100%'></img>
</LazyLoad>
)
})
:<span></span>}
</div>
)
}
}
react-lazyload的项目地址:https://github.com/twobin/react-lazyload