懒加载 React 长页面 - 动态渲染组件

578次阅读  |  发布于3年以前

背景

长页面在前端开发中是非常常见的。例如下图中的电商首页,楼层数据来自运营人员在后台的配置,楼层数量是不固定的,同时每个楼层可能会依赖更多翻页数据。在这种情况下,如果一次性将页面全部渲染,可想而知,我们的页面直出效率(fmp, fid)会受到影响。

为了更好的用户体验,我们需要考虑在用户滚动到下一屏时,渲染下一屏的组件。

设计思路

假设页面预期渲染 n 个组件,每个组件均会触发请求其他接口。设计这样一个长页面,我们主要会面临以下两个问题:

图 1

一、渲染下一屏的时机

1. 初始定义

以首页为例,我们将楼层数据源用 homeInfo 变量保存,而实际渲染的数据用 compList 保存。另外,我们需要一个 loading 组件,该组件始终处于楼层组件的最下方。

const homeInfo = [...楼层数据];
const [compList, setCompList] = useState([]); // 渲染的组件数据
const bottomDomRef = useRef<HTMLDivElement>(null);
// 楼层组件
<div>
   {compList.map((homeItem, index) => (
     <div className="home-floor" key={index}>
         // 根据不同的楼层渲染不同的楼层组件
        {renderHomeConfig(homeItem)}
      </div>
   ))}
</div>

// loading DOM
<div ref={bottomDomRef} className='bottom-loading'>
  <Icon name="loading" />
</div>

// completed DOM
<div className="bottom-completed">
   <p>已经到底啦</p>
</div>

2. Loading 组件是否在视图内

如图 1 所示,当 loading 组件的位置滚动到视图中时,并且如果此时还有未渲染的组件,这时便是渲染下一屏的时机。

判断组件是否在视图内有两种方式,一种是调用调用Element.getBoundingClientRect\(\)[1]方法以获取 loading 元素的边界信息,进行判断,另一种是调用Intersection Observer API[2]进行判断。

方法 1:getBoundingClientRect

我们需要知道 窗口高度 以及 Loading 组件的高度。

Element.clientHeight 元素内部的高度,包含内边距,但不包括水平滚动条、边框和外边距。

Element.scrollHeight 元素内容高度的度量,包括由于溢出导致的视图中不可见内容。

Element.getBoundingClientRect() 方法返回元素的大小及其相对于视口的位置。

const scrollRenderHandler = ():void => {
    const rect = bottomDomRef.current?.getBoundingClientRect();
    // top 是loading组件的位置
    const top = rect ? rect.top : 0;
    // 视窗高
    const clientHeight = document.documentElement.clientHeight
                        || document.body.clientHeight;
    if (top < clientHeight &&  组件没渲染完) {
        // 继续渲染
    }
}

 useEffect(() => {
    document.addEventListener('scroll', scrollRenderHandler);
    return (): void => {
      document.removeEventListener('scroll', scrollRenderHandler);
    };
  }, [scrollRenderHandler]);
方法 2:Intersection Observer

使用 react-intersection-observer 的 api 判断 loading 元素是否在视图内。

// Use object destructing, so you don't need to remember the exact order
const { ref, inView, entry } = useInView(options);
// Or array destructing, making it easy to customize the field names
const [ref, inView, entry] = useInView(options);
import { useInView } from 'react-intersection-observer';

const [bottomDomRef, inView] = useInView({
   threshold: 0,
});

const scrollRenderHandler = ():void => {
    if (inView &&  组件没渲染完) {
        // 继续渲染
    }
}

3. 组件是否渲染完成

假设一屏展示 3 个组件,类似常见分页逻辑中的 pageSize = 3,我们可以将 n 个组件分割成每 3 个 1 组,对每组依次进行渲染,并用 compGroups 保存分割的组,同时使用 groupIdx 指针来指向下一个需要渲染的组序列。

export const splitGroups = (homeList: any[], pageSize: number): any[] => {
  const groupsTemp = [];
  for (let i = 0; i < homeList.length; i += pageSize) {
    groupsTemp.push(homeList.slice(i, i + pageSize));
  }
  return groupsTemp;
};

const compGroups = useMemo(() => splitGroups(homeInfo, 3), [homeInfo]);
const groupCount = compGroups.length;
const [groupIdx, setGroupIdx] = useState(0);

当分割好组后,如何判断组件没渲染完的问题便迎刃而解,当 groupIdx 小于 groupCount,更新 compList 和 groupIdx。

if (top < clientHeight && groupIdx < compGroups.length) {
    setCompList(compList.concat(compGroups[groupIdx]));
    setGroupIdx(groupIdx + 1);

 }

4. 监听滚动优化

在滚动时会频繁触发 scrollRenderHandler 函数,导致页面性能低下。此时需要采用节流,并用 useCallback 缓存 scrollRenderHandler 函数用来提升性能。

const [scrollRenderHandler] = useDebounce((): void => {
    if (inView && groupIdx < groupCount) {
      setCompList(compList.concat(compGroups[groupIdx]));
      setGroupIdx(groupIdx + 1);
    }
  },
  300,
  [compGroups, compList, groupIdx, inView],
 );

 useEffect(() => {
    document.addEventListener('scroll', scrollRenderHandler);
    return (): void => {
      document.removeEventListener('scroll', scrollRenderHandler);
    };
 }, [scrollRenderHandler]);

export default function useDebounce<T extends(...args: any[]) => any>(
  func: T,
  delay: number,
  deps: DependencyList = [],
): [T, () => void] {
  const timer = useRef<number>();
  const cancel = useCallback(() => {
    if (timer.current) {
      clearTimeout(timer.current);
    }
  }, []);

  const run = useCallback((...args) => {
    cancel();
    timer.current = window.setTimeout(() => {
      func(...args);
    }, delay);
  }, deps);
  return [run as T, cancel];
}

二、不重复发起数据请求

1. 症结分析

至此,随着屏幕滚动,我们基本完成了组件动态渲染的要求。但还有另外一个问题:随着滚动,相同的数据接口请求了多次。

如上图,同一楼层的接口被请求了两遍。这意味着,在窗口滚动的过程中,我们反复更新了 compList 数据,从而导致了楼层组件重新渲染,而每个楼层组件的数据请求,是放在组件内部的,这与该楼层的唯一标识 uuid 相关,因此导致数据接口的重复请求。

2. React.memo

React Top-Level API – React[3]

通过上述症结我们得知,只要组件不重复渲染,便可规避掉重复请求的问题。

在没有引入 React.memo 之前,使用 PureComponent 可以达到对 props 浅比较的效果,另外,我们也可以采用 shouldComponentUpdate 来进行具体的比较,从而减少组件的渲染次数。

具体如:shouldComponentUpdate(nextProps, nextState)而在函数组件中,我们可以使用 React.memo ,它的使用方法非常简单,如下所示。如果不传 areEqual 则对 props 进行浅比较。若传入,则需要返回具体的比较结果 true, false 。

function MyComponent(props) {
  /* render using props */
}
function areEqual(prevProps, nextProps) {
  /*
  return true if passing nextProps to render would return
  the same result as passing prevProps to render,
  otherwise return false
  */
}
export default React.memo(MyComponent, areEqual);

因此,我们只需要在对应的楼层组件中,将组件用 memo 进行包裹,并对比它们的唯一标识 uuid 。

代码如下:

import React, { memo } from 'react';
type GoodsRecommedProps = {
    ...其他 props,
    goodsQuery:{
        uuid: '...'
    }
}

const GoodsRecommed: React.FC<GoodsRecommedProps> = (props) => {
    ...
}

const isEqual = (prevProps: GoodsRecommedProps, nextProps: GoodsRecommedProps): boolean => {
  if (prevProps.goodsQuery.uuid !== nextProps.goodsQuery.uuid) {
    return false;
  }
  return true;
};

export default memo(GoodsRecommed, isEqual);

最后看一下效果,确实没有重复的数据请求了。

总结

在写一个普通的长页面的过程中,如果只追求完成,那么将会非常简单,但如果想要进一步优化,那可做的事情就有很多了。

参考资料

[1]Element.getBoundingClientRect(): https://developer.mozilla.org/zh-CN/docs/Web/API/Element/getBoundingClientRect

[2]Intersection Observer API: https://developer.mozilla.org/zh-CN/docs/Web/API/Intersection_Observer_API

[3]React Top-Level API – React: https://reactjs.org/docs/react-api.html#reactmemo

[4]React Top-Level API – React: https://reactjs.org/docs/react-api.html#reactmemo

[5]Element.getBoundingClientRect() - Web API 接口参考 | MDN: https://developer.mozilla.org/zh-CN/docs/Web/API/Element/getBoundingClientRect

[6]IntersectionObserver API 使用教程 - 阮一峰的网络日志: http://www.ruanyifeng.com/blog/2016/11/intersectionobserver_api.html

[7]精读《react-intersection-observer 源码》: https://zhuanlan.zhihu.com/p/149926289

[8]useCallback、useMemo 分析 & 差别: https://juejin.cn/post/6844904001998176263#heading-7

[9]thebuilder/react-intersection-observer: https://github.com/thebuilder/react-intersection-observer

[10]React 如何渲染大数据量的列表?: https://juejin.cn/post/6844903634036064270

Copyright© 2013-2020

All Rights Reserved 京ICP备2023019179号-8