背景
长页面在前端开发中是非常常见的。例如下图中的电商首页,楼层数据来自运营人员在后台的配置,楼层数量是不固定的,同时每个楼层可能会依赖更多翻页数据。在这种情况下,如果一次性将页面全部渲染,可想而知,页面直出效率(fmp, fid)会受到影响。
为了更好的用户体验,需要考虑在用户滚动到下一屏时,渲染下一屏的组件。
设计思路
假设页面预期渲染 n 个组件,每个组件均会触发请求其他接口。设计这样一个长页面,主要会面临以下两个问题:
- 渲染下一屏组件的时机应该如何判断?
- 在数据反复更新的过程中,如何让组件不重复发起数据请求?
一、渲染下一屏的时机
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()](https://developer.mozilla.org/zh-CN/docs/Web/API/Element/getBoundingClientRect)方法以获取 loading 元素的边界信息,进行判断,另一种是调用Intersection Observer API进行判断。
方法 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 orderconst { ref, inView, entry } = useInView(options);// Or array destructing, making it easy to customize the field namesconst [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
通过上述症结得知,只要组件不重复渲染,便可规避掉重复请求的问题。
在没有引入 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 returnthe 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);
总结
React.memo用于组件单位的性能优化。useCallback根据依赖缓存第一个参数的callback,多用于缓存函数。useMemo根据依赖缓存的第一个参数的返回值,多用于组件内更细粒度的某一部分性能优化。


