我正在使用Infinite scroll component。它正在工作,但是它多次请求相同的端点(3-4次)。利用我的React知识,让我解释发生了什么:
因为我要设置 initialLoad = {true} ,所以loadMore函数将在组件渲染后立即调用。我可以设置 initialLoad = {false} ,但是它不能在初始渲染中获取数据
Index.js
export default function index() {
const { tracks, error, loading, loadMore, hasMore } = usePublicTracks(
myApiEndPoint.TRENDING_TRACKS,
5,
);
return (
<div>
<Main>
<InfiniteScroll
initialLoad={true} //call loadMore function right after component rendered
pageStart={0}
loadMore={loadMore}
hasMore={hasMore}
>
<TrackList>
{tracks.map((track, i) => (
<TrackItem key={i}
track={track}
/>
))}
</TrackList>
{loading && hasMore && (
<div className="">
<Spin />
</div>
)}
</InfiniteScroll>
</Main>
</div>
);
}
usePublicTracks.js
export const usePublicTracks = (endpoint, limit) => {
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const [offset, setOffset] = useState('');
const [tracks, setTracks] = useState([])
const [hasMore, setHasMore] = useState(true);
console.log('tracks', tracks)
const loadMore = async params => {
try {
console.log('hello22222222222222222222222222222222222222222')
const res = await myApiAxiosInstance.get(endpoint, {
params: {
limit: limit,
lastVisible: offset
}
});
setLoading(false);
setTracks([...tracks, ...(res.data.collection)])
setOffset(res.data.lastVisible)
if (res.data.lastVisible == "end") setHasMore(false);
} catch (error) {
setLoading(false);
setError(error.message);
}
};
return {
error,
loading,
tracks,
loadMore,
hasMore
};
};
当我在 useEffect 中包装loadMore函数时,它显示错误只能在函数组件主体内部调用挂钩。:
const loadMore = async params => {
useEffect(() => {
const loadMoreOnce = async () => {
//some logic
};
loadMoreOnce();
}, []);
};
我的问题是如何调用一次load more函数。然后每次滚动到窗口底部时都调用它吗?如何防止多次请求同一终结点?
答案 0 :(得分:1)
const isLoading = false;
const myComponent = () => {
useEffect(() => {
loadMore(); // initial call, this useEffect equivalent to componentDidMount
}, []);
if (!isLoading && document.body.scrollTop >= document.body.offsetTop) {
console.log('loading, should see this once');
isLoading = true;
loadMore(); // here, after loadMore finished you need to resolve isLoading to false
}
return (<div>My component</div>);
}
尝试查找所有的loadMore函数调用,也可能在其他一些地方调用,从页面开始更改偏移量,检查hasMore条件是否正确跟踪,因为当InfiniteScroll本身也有多个调用时,它认为您多次触底。