首頁 > 軟體

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

2023-03-25 06:00:47

應用場景

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

效果預覽

思路剖析

  • 設定臨界元素,當臨界元素進入可視範圍時請求並追加新資料。
  • 根據可視視窗和捲動元素組建的關係確定資料載入時機。
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;

總結

以上為個人經驗,希望能給大家一個參考,也希望大家多多支援it145.com。


IT145.com E-mail:sddin#qq.com