使用JSON数据在ReactJS中实现无限滚动

jtoj6r0c  于 2023-05-06  发布在  React
关注(0)|答案(1)|浏览(125)
function App() {
  const [response, setResponse] = useState([]);
  const [page, setPage] = useState(10);
  // const [data, setData] = useState([]);
  const count = useRef();

  useEffect(() => {
    fetch(`https://jsonplaceholder.typicode.com/comments`)
      .then(response => response.json())
      .then(json => getTenDataFirst(json));
  }, []);

  function getTenDataFirst(data) {
    data.splice(page)
    setResponse(data)
  }

  const handelInfiniteScroll = async () => {
    console.log("scrollHeight" + count.current.scrollHeight);
    console.log("innerHeight" + count.current.innerHeight);
    console.log("scrollTop" + count.current.scrollTop);
  };

  return (
    <div className='container'>
      <div className='box' ref={count} onScroll={() => handelInfiniteScroll()}>
        {
          response?.length > 0 && response?.map((data) => {
            return (
              <div key={data['id']}>{data['name']}</div>
            )
          })
        }
      </div>
    </div>
  );
}

export default App;

在reactjs中使用json data实现无限滚动,但onscroll得到innerHeight undefined。有没有其他方法可以在reactjs中实现无限滚动而不使用第三方库或JavaScript语法

idfiyjo8

idfiyjo81#

您可以使用IntersectionObserver API来实现这一点。
一个简单的钩子看起来像这样:

const useOnScreen = (ref) => {
  const [isIntersecting, setIntersecting] = useState(false);

  const observer = useMemo(
    () =>
      new IntersectionObserver(([entry]) =>
        setIntersecting(entry.isIntersecting)
      ),
    [ref]
  );

  useEffect(() => {
    observer.observe(ref?.current);
    return () => observer.disconnect();
  }, []);

  return isIntersecting;
};

// usage of hook
const bottomRef = useRef(null);
const isVisible = useOnScreen(bottomRef);
    
return (
  <div>
    // list of items here
    <div ref={bottomRef}/>
  </div>
)

相关问题