原生+React實現懶加載(無限滾動)列表方式

應用場景

懶加載列表或叫做無限滾動列表,也是一種性能優化的方式,其可疑不必一次性請求所有數據,可以看做是分頁的另一種實現形式,較多適用於移動端提升用戶體驗,新聞、資訊瀏覽等。

效果預覽

思路剖析

  • 設置臨界元素,當臨界元素進入可視范圍時請求並追加新數據。
  • 根據可視窗口和滾動元素組建的關系確定數據加載時機。
container.clientHeight - wrapper.scrollTop <= wrapper.clientHeight 

原生代碼實現

index.html

<body>
  <div id="wrapper" onscroll="handleScroll()">
    <ul id="container"></ul>
  </div>
  <script type="text/javascript" src="./index.js"></script>
</body>

index.css

* {
  margin: 0;
  padding: 0;
}
#wrapper {
  margin: 100px auto;
  width: 300px;
  height: 300px;
  border: 1px solid rgba(100, 100, 100, 0.2);
  overflow-y: scroll;
}

ul#container {
  list-style: none;
  padding: 0;
  width: 100%;
}
ul#container > li {
  height: 30px;
  width: 100%;
}
ul#container > li.green-item {
  background-color: #c5e3ff;
}
ul#container > li.red-item {
  background-color: #fff5d5;
}

index.js

// 模擬數據構造
const arr = [];
const nameArr = ['Alice', 'July', 'Roman', 'David', 'Sara', 'Lisa', 'Mike'];

let curPage = 1;
let noData = false;
const curPageSize = 20;
const getPageData = (page, pageSize) => {
  if (page > 5) return [];
  const arr = [];
  // const nameArr = ['Alice', 'July', 'Roman', 'David', 'Sara', 'Lisa', 'Mike'];
  for (let i = 0; i < pageSize; i++) {
    arr.push({
      number: i + (page - 1) * pageSize,
      name: `${nameArr[i % nameArr.length]}`,
    });
  }
  return arr;
};

const wrapper = document.getElementById('wrapper');
const container = document.getElementById('container');
let plainWrapper = null;

/**
 * @method handleScroll
 * @description: 滾動事件監聽
 */
const handleScroll = () => {
  // 當臨界元素進入可視范圍時,加載下一頁數據
  if (
    !noData &&
    container.clientHeight - wrapper.scrollTop <= wrapper.clientHeight
  ) {
    curPage++;
    console.log(curPage);
    const newData = getPageData(curPage, curPageSize);
    renderList(newData);
  }
};

/**
 * @description: 列表渲染
 * @param {Array} data
 */
const renderList = (data) => {
  // 沒有更多數據時
  if (!data.length) {
    noData = true;
    plainWrapper.innerText = 'no more data...';
    return;
  }
  plainWrapper && container.removeChild(plainWrapper); //移除上一個臨界元素
  const fragment = document.createDocumentFragment();
  data.forEach((item) => {
    const li = document.createElement('li');
    li.className = item.number % 2 === 0 ? 'green-item' : 'red-item'; //奇偶行元素不同色
    const text = document.createTextNode(
      `${`${item.number}`.padStart(7, '0')}-${item.name}`
    );
    li.appendChild(text);
    fragment.appendChild(li);
  });
  const plainNode = document.createElement('li');
  const text = document.createTextNode('scroll to load more...');
  plainNode.appendChild(text);
  plainWrapper = plainNode;
  fragment.appendChild(plainNode); //添加新的臨界元素
  container.appendChild(fragment);
};

// 初始渲染
renderList(getPageData(curPage, curPageSize));

遷移到React

React 中實現時可以省去復雜的手動渲染邏輯部分,更關註數據。

store/data.ts

import { IDataItem } from '../interface';
const nameArr = ['Alice', 'July', 'Roman', 'David', 'Sara', 'Lisa', 'Mike'];

export const getPageData = (
  page: number = 1,
  pageSize: number = 10
): Array<IDataItem> => {
  if (page > 5) return [];
  const arr = [];
  // const nameArr = ['Alice', 'July', 'Roman', 'David', 'Sara', 'Lisa', 'Mike'];
  for (let i = 0; i < pageSize; i++) {
    arr.push({
      number: i + (page - 1) * pageSize,
      name: `${nameArr[i % nameArr.length]}`,
    });
  }
  return arr;
};

LazyList.tsx

/*
 * @Description: 懶加載列表(無限滾動列表)
 * @Date: 2021-12-20 15:12:15
 * @LastEditTime: 2021-12-20 16:04:18
 */
import React, { FC, useCallback, useEffect, useReducer, useRef } from 'react';
import { getPageData } from './store/data';
import { IDataItem } from './interface';

import styles from './index.module.css';

export interface IProps {
  curPageSize?: number;
}

export interface IState {
  curPage: number;
  noData: boolean;
  listData: Array<IDataItem>;
}
const LazyList: FC<IProps> = ({ curPageSize = 10 }: IProps) => {
  const clientRef: any = useRef(null);
  const scrollRef: any = useRef(null);

  const [state, dispatch] = useReducer(
    (state: IState, action: any): IState => {
      switch (action.type) {
        case 'APPEND':
          return {
            ...state,
            listData: [...state.listData, ...action.payload.listData],
          };
        default:
          return { ...state, ...action.payload };
      }
    },
    {
      curPage: 1,
      noData: false,
      listData: [],
    }
  );
  /**
   * @method handleScroll
   * @description: 滾動事件監聽
   */
  const handleScroll = useCallback(() => {
    const { clientHeight: wrapperHeight } = scrollRef.current;
    const { scrollTop, clientHeight } = clientRef.current;

    // 當臨界元素進入可視范圍時,加載下一頁數據
    if (!state.noData && wrapperHeight - scrollTop <= clientHeight) {
      console.log(state.curPage);
      const newData = getPageData(state.curPage, curPageSize);
      dispatch({
        type: 'APPEND',
        payload: { listData: newData },
      });
      dispatch({
        payload: {
          curPage: state.curPage + 1,
          noData: !(newData.length > 0),
        },
      });
    }
  }, [state.curPage, state.noData]);

  useEffect(() => {
    const newData = getPageData(1, curPageSize);
    dispatch({
      type: 'APPEND',
      payload: { listData: newData },
    });
    dispatch({
      payload: {
        curPage: 2,
        noData: !(newData.length > 0),
      },
    });
  }, []);

  return (
    <div className={styles[`wrapper`]} ref={clientRef} onScroll={handleScroll}>
      <ul className={styles[`container`]} ref={scrollRef}>
        {state.listData.map(({ number, name }) => (
          <li
            key={number}
            className={
              number % 2 === 0 ? styles[`green-item`] : styles[`red-item`]
            }
          >
            {number}-{name}
          </li>
        ))}
        {<li>{state.noData ? 'no more' : 'scroll'}</li>}
      </ul>
    </div>
  );
};
export default LazyList;

總結

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: