TIL
TIL 무한스크롤 구현 aixos 편
Jaeilit
2021. 10. 22. 00:36
728x90
import React, { useCallback, useEffect, useState } from "react"
import _ from "lodash"
export const InfinityScroll = (props) => {
const { children, callNext, is_next, loading } = props
const _handleScroll = _.throttle(() => {
const { innerHeight } = window
const { scrollHeight } = document.body
// 스크롤 계산!
const scrollTop =
(document.documentElement && document.documentElement.scrollTop) ||
document.body.scrollTop
if (scrollHeight - innerHeight - scrollTop < 200) {
if (loading) {
return
}
callNext()
}
}, 300)
const handleScroll = useCallback(_handleScroll, [loading])
useEffect(() => {
if (is_next) {
window.addEventListener("scroll", handleScroll)
} else {
window.removeEventListener("scroll", handleScroll)
}
return () => window.removeEventListener("scroll", handleScroll)
}, [is_next, loading])
return <>{children}</>
}
InfinityScroll.defaultProps = {
children: null,
callNext: () => {},
is_next: false,
loading: false,
}
로데쉬의 쓰로틀을 걸어서 3초마다 스크롤을 추적하게 만듬
스크롤 위치가 바닥에서 200남기면 callNext 로 다음꺼를 불러오는 로직
useCallback 으로 스크롤 계산값을 메모이제이션 해놓고
useEffect 로 scroll 이벤트르 일으킴,
const [view, setView] = useState({
start: 0,
next: 2,
})
useEffect(() => {
dispatch(postActions.getPostMD(view))
}, [comment_list, view])
// console.log(is_loading, "isloading")
return (
<InfinityScroll
callNext={() => {
setView({
// ...view,
start: view.start,
next: (view.next += 2),
})
}}
is_next={true}
loading={is_loading}
>
리덕스 부분에서 getPost로 res.data 를 slice 해서 가져오기 때문에
slice 할 값을 state 로 컨트롤 하여 넘겨줌
처음 start 0
그 다음값 next = 2
스크롤이 바닥을 치면 실행되는 callNext 함수 안에 setView 로 start 는 기본 0 이고
next 는 현재 view 값의 +=2 누적값을 더해줌
오류나는 부분은 is_next 가 제 역할을 못하고있기 때문에 true 값을 고정으로 주었고
그로인해 지금 바닥을 치면 가져올게 없는데도 자꾸 +=2를 하게 됨,
내일 수정해야합니다.
728x90