React中使用LazyBuilder实现页面懒加载方法一

前言:

        在一个表格中,需要展示100条数据,当每条数据里面需要承载的内容很多,需要渲染的元素也很多的时候,容易造成页面加载的速度很慢,不能给用户提供很好的体验时,懒加载是优化页面加载速度的方法之一。

策略:

        前端在接受到api返回的数据的时候,可以先根据数据总的条数进行遍历,给每一项初始化简单的dom进行渲染占位,通过IntersectionObserver对每一项元素进行监听,当初始dom出现在页面视口的时候,需要替换掉初始dom,渲染真实dom,同样,在初始dom隐藏在页面视口后,我们再去替换掉真实dom,渲染初始dom。这样可以实现:只有出现在视口内的元素才渲染真实的dom,在视口以外的元素都渲染初始dom,首次加载多少个真实dom,取决于可视区域跟初始dom的高度

React中使用LazyBuilder实现页面懒加载方法二

与方法二不同之处:

方法一:元素出现在可视区域内,即渲染真实dom,一旦消失在可视区域内,即渲染初始dom

方法二:元素只要出现在可视区域内一次,即渲染真实dom,并且取消对该dom的监听,只需加载一次

LazyBuilder.jsx

import React, { Component, createRef } from "react";
class LazyBuilder extends Component {
  static defaultProps = {
      initComponent: null,
      initHeight: null,
      controller: null,
      className: null,
      style: null,
  }
  /**
   * @param {Object} props
   * @param {JSX.Element} [props.initComponent] - 默认组件
   * @param {Number} [props.initHeight] - 组件高度
   * @param {LazyController} [props.controller] - LazyController
   */
  constructor(props) {
    super(props);
    this._ref = createRef();
    this.controller = this.props.controller instanceof LazyController ? this.props.controller : new LazyController();
    this.state = {
        isLoading: undefined,
        firstIsLoading: true, // 作用:在页面进行初始渲染时,所有的项都设置初始dom
        initStyle: {
          width: "100%",
          height: props.initHeight
        },
        key: `lazy_${Math.random().toString(16).slice(2)}`,
    }
  }

  componentDidMount() {
    // 页面初始化时,对所有元素进行绑定监听
    this.controller.observe(this._ref.current, this.updateShowElement.bind(this));
  }

  updateShowElement = (type) => {
    const {initHeight} = this.props
    if(type == 1){
      // 元素出现在视口以内
      this.setState({
        isLoading: false,
        firstIsLoading: false,
        initStyle: null,
      });
    } else if(type == 2) {
      // 元素出现在视口以外
      this.setState({
        isLoading: true,
        initStyle: {
          width: "100%",
          height: initHeight
        },
      });
    }
  }

  render () {
    const { children, initComponent } = this.props;
    const { isLoading, initStyle, firstIsLoading} = this.state;
    const className = ["lazy-builder-item", this.props.className].filter(item => typeof item === "string").join("\s");
    return (
        <div id={this.state.key} ref={this._ref} className={className} style={Object.assign({}, initStyle, this.props.style)}>
          {
            firstIsLoading
            ? initComponent
            : isLoading ? initComponent : children
          }
        </div>
    );
  }
}

class LazyController {
  constructor(){

    // 定义map来存储所有的dom项
    this._map = new Map();

    // IntersectionObserver 对每一项元素进行监听
    this.observer = new IntersectionObserver((entries) => {
      for (const entry of entries) {
        const updateShowElement = this._map.get(entry.target);
        // isIntersecting: true - 出现在视口    false - 隐藏(视口以外)
        if (entry.isIntersecting) {
          if (typeof updateShowElement === "function") {
            updateShowElement(1)
          }
        } else {
          if (typeof updateShowElement === "function") {
            updateShowElement(2)
          }
        }
      }
    });
  }

  // 观察指定DOM
  observe = (target, callback) => {
    if (this.observer && !this.has(target)) {
      // 初始化时,将每一项保存在map中
      this._map.set(target, callback);
      this.observer.observe(target);
    }
  }

  // 判断一个DOM是否正在被观察
  has = (target) => {
    return this._map.has(target);
  }

}

export {
  LazyBuilder,
  LazyController,
}

cp.jsx

import React, {Component} from 'react';
import { LazyBuilder, LazyController } from './LazyBuilder'
export default class  Cp extends Component {
  constructor(props){
    super(props)

    // 创建controller
    this.controller = new LazyController();
    this.state = {
      // 模拟数据
      dataList: new Array(100).fill().map((item, index) => index + 1)
    }
  }

  render(){
    const {dataList} = this.state
    return (
      <div>
        {
          Array.isArray(dataList) && dataList.length > 0
          ? dataList.map((item, index) => {
            return <LazyBuilder 
                    key={index}
                    initHeight={100} // 初始dom高度
                    controller={this.controller} // controller
                  >
                    <div style={{width: '100%', height: '200px'}}>{`第${item}个元素`}</div>
                  </LazyBuilder>
          })
          : null
        }
      </div>
    )
  }
}

效果

页面刚加载时,只有前面几条数据在视口内 

经过滚动后

  • 6
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小灰灰学编程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值