借助IntersectionObserver实现LoadMore组件,无限下拉加载数据。边界控制没有处理
LoadMore.tsx:
import React, { useEffect, useRef } from "react";
import "./index.css";
/**
.load-more {
height: 100px;
background: #eee;
text-align: center;
line-height: 100px;
}
**/
function LoadMore(props) {
const ref = useRef();
const loadMoreRef = useRef(()=>{});
loadMoreRef.current = props.loadMore;//持久化函数
useEffect(() => {
console.log("loadMore");
const observer = new IntersectionObserver(entries => {
if (entries[0].intersectionRatio <= 0) return;
console.log(entries);
loadMoreRef.current && loadMoreRef.current();
});
observer.observe(ref.current);
return () => {
observer.disconnect();
};
}, []);
return (
<div className="load-more" ref={ref}>
加载更多
</div>
);
}
export default LoadMore;
App.tsx
import React, { useState, useCallback } from "react";
import ReactDOM from "react-dom";
import LoadMore from "./LoadMore";
import "./index.css";
/**
.card {
margin: 20px;
border: 1px solid #ddd;
border-radius: 6px;
height: 60px;
line-height: 60px;
}
**/
const App: React.FC = () => {
const [list, setList] = useState(() => {
return new Array(20).fill(0); //只会执行一次初始化数据
});
return (
<div>
{list.map((item, index) => (
<div className="card" key={index}>
{item}
</div>
))}
<LoadMore
loadMore={() => {
console.log("加载更多");
setTimeout(() => {
const newList = new Array(20).fill(Math.random());
setList([...list, ...newList]);
}, 1000);
}}
/>
</div>
);
};
ReactDOM.render(<App />, document.getElementById("root"));
1312

被折叠的 条评论
为什么被折叠?



