React中使用LazyBuilder实现页面懒加载方法一 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>
    )
  }
}

效果

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

经过滚动后

相关推荐

  1. React

    2024-01-29 10:50:01       21 阅读
  2. React和Vue实现路由

    2024-01-29 10:50:01       31 阅读
  3. React和Vue实现路由

    2024-01-29 10:50:01       26 阅读
  4. React和Vue实现路由

    2024-01-29 10:50:01       32 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-01-29 10:50:01       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-29 10:50:01       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-29 10:50:01       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-29 10:50:01       18 阅读

热门阅读

  1. Ubuntu系统桌面卡死,解决办法

    2024-01-29 10:50:01       34 阅读
  2. 计算机视觉(CV)技术的优势和挑战

    2024-01-29 10:50:01       30 阅读
  3. 【漏洞复现】金蝶云星空-AppDesigner-反序列化-rce

    2024-01-29 10:50:01       35 阅读
  4. Vue3+Echarts实现实时曲线及开始与暂停功能

    2024-01-29 10:50:01       30 阅读
  5. Qlik Sense : IntervalMatch(离散匹配)

    2024-01-29 10:50:01       29 阅读
  6. Leetcode 3021. Alice and Bob Playing Flower Game

    2024-01-29 10:50:01       36 阅读
  7. 记录 | ubuntu查看系统信息如系统版本、cpu信息

    2024-01-29 10:50:01       33 阅读
  8. ubuntu 添加 sudo 权限

    2024-01-29 10:50:01       31 阅读
  9. Matlab自学笔记二十六:sprintf函数用法简介

    2024-01-29 10:50:01       38 阅读