数据多且不分页,前端渲染dom如何优化性能

  1. js判断子节点有没有进入父节点可视区域

在React项目中,你可以使用useEffect钩子和IntersectionObserver API来实现这个功能。下面是一个例子:

首先,创建一个子组件 ChildComponent

import React, { useEffect, useRef } from 'react';

const ChildComponent = () => {
  const childRef = useRef(null);

  useEffect(() => {
    const observer = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          console.log('子节点进入可视区域');
        } else {
          console.log('子节点离开可视区域');
        }
      });
    });

    observer.observe(childRef.current);

    // 清除观察器
    return () => {
      observer.disconnect();
    };
  }, []);

  return <div ref={childRef}>子节点内容</div>;
};

export default ChildComponent;

然后,父组件中使用ChildComponent组件:

import React from 'react';
import ChildComponent from './ChildComponent';

const ParentComponent = () => {
  return (
    <div style={
   
   { height: '300px', overflowY: 'scroll' }}>
      {Array.from({ length: 10 }, (_, index) => (
        <ChildComponent key={index} />
      ))}
    </div>
  );
};

export default ParentComponent;

在这个例子中,ChildComponent组件在可视区域内进入或离开时会在控制台输出相应的消息。这个组件会在useEffect钩子中创建一个IntersectionObserver实例,监听子节点是否进入父节点的可视区域。

请确保适当地调整代码以适应你的实际情况,比如根据你的数据渲染方式,可能需要传递一些参数给子组件或者动态地计算子节点的数量。

  1. 懒加载插件(这个插件原理就是1中所述):react-lazyload

https://github.com/twobin/react-lazyload#readme
图片的懒加载也可是这个

PS:如果是分页的数据,ant-design中有个List组件和react-infinite-scroll-component插件搭配使用,类似app中的滑动加载
react-infinite-scroll-component组件使用需要注意:

  1. 全部项目中,多个地方引用,一定要注意id唯一;
  2. 在Drawer等弹框组件中使用,注意将弹框组件挂载的节点设置成id:root的div上

猜你喜欢

转载自blog.csdn.net/weixin_43925630/article/details/138522042