import React, { useEffect, useRef } from "react";
import styles from "../../index.less";

interface OwnProps {}

type Props = OwnProps;

const Index: React.FC<Props> = (props) => {
  const itemRef = useRef<HTMLElement[]>([]);
  const ob = new IntersectionObserver((entries) => {
    for (const entry of entries) {
      if (entry.isIntersecting) {
        const img: any = entry.target;
        img.src = img.dataset.src;
        ob.unobserve(entry.target);
      }
    }
  });
  useEffect(() => {
    if (itemRef.current) {
      _.forEach(itemRef.current, (item) => {
        ob.observe(item);
      });
    }

    return () => {
      if (itemRef.current) {
        _.forEach(itemRef.current, (item) => {
          ob.unobserve(item);
        });
      }
    };
  }, [itemRef.current]);
  return (
    <ul className={styles.lazyloadImg}>
      {_.map(
        Array.from({ length: 200 }, () => Math.floor(Math.random() * 100)),
        (item, index) => (
          <li key={index}>
            <img data-src={`https://picsum.photos/300/300?random=${index}`} alt="" src={require("../default.jpeg")} ref={(el) => (itemRef.current[index] = el as HTMLElement)} />
          </li>
        )
      )}
    </ul>
  );
};

export default Index;
