• 카테고리

    질문 & 답변
  • 세부 분야

    풀스택

  • 해결 여부

    미해결

잘들었습니다선생님

20.03.24 16:09 작성 조회수 150

3

잘들었습니다선생님. 근데 혹시 read more를 자동으로 실행시키도록 할순 없을까요? 페이스북처럼요. 스크롤을 내리면 실행되게끔 할 순 없나요?

답변 2

·

답변을 작성해보세요.

3

Landing 페이지 소스를 이걸로 바꿔 주세요 ^^ ~~ 

제가 예전에 그냥 만들어 놓은 건데 

원리는 페이지 내려갈 때 자동으로 load more 버튼을 눌러주는 형식으로 만들어봤습니다 ^^

import React, { useEffect, useState, useRef } from 'react'
import { Typography, Row, Button } from 'antd';
import { API_URL, API_KEY, IMAGE_BASE_URL, IMAGE_SIZE, POSTER_SIZE } from '../../Config'
import MainImage from './Sections/MainImage'
import GridCard from '../../commons/GridCards'
const { Title } = Typography;
function LandingPage() {
const buttonRef = useRef(null);

const [Movies, setMovies] = useState([])
const [MainMovieImage, setMainMovieImage] = useState(null)
const [Loading, setLoading] = useState(true)
const [CurrentPage, setCurrentPage] = useState(0)

useEffect(() => {
const endpoint = `${API_URL}movie/popular?api_key=${API_KEY}&language=en-US&page=1`;
fetchMovies(endpoint)
}, [])

useEffect(() => {
window.addEventListener("scroll", handleScroll);
}, [])


const fetchMovies = (endpoint) => {

fetch(endpoint)
.then(result => result.json())
.then(result => {
// console.log(result)
// console.log('Movies',...Movies)
// console.log('result',...result.results)
setMovies([...Movies, ...result.results])
setMainMovieImage(MainMovieImage || result.results[0])
setCurrentPage(result.page)
}, setLoading(false))
.catch(error => console.error('Error:', error)
)
}

const loadMoreItems = () => {
let endpoint = '';
setLoading(true)
console.log('CurrentPage', CurrentPage)
endpoint = `${API_URL}movie/popular?api_key=${API_KEY}&language=en-US&page=${CurrentPage + 1}`;
fetchMovies(endpoint);

}

const handleScroll = () => {
const windowHeight = "innerHeight" in window ? window.innerHeight : document.documentElement.offsetHeight;
const body = document.body;
const html = document.documentElement;
const docHeight = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight);
const windowBottom = windowHeight + window.pageYOffset;
if (windowBottom >= docHeight - 1) {

// loadMoreItems()
console.log('clicked')
buttonRef.current.click();

}
}

return (
<div style={{ width: '100%', margin: '0' }}>
{MainMovieImage &&
<MainImage
image={`${IMAGE_BASE_URL}${IMAGE_SIZE}${MainMovieImage.backdrop_path}`}
title={MainMovieImage.original_title}
text={MainMovieImage.overview}
/>

}

<div style={{ width: '85%', margin: '1rem auto' }}>

<Title level={2} > Movies by latest </Title>
<hr />
<Row gutter={[16, 16]}>
{Movies && Movies.map((movie, index) => (
<React.Fragment key={index}>
<GridCard
image={movie.poster_path ?
`${IMAGE_BASE_URL}${POSTER_SIZE}${movie.poster_path}`
: null}
movieId={movie.id}
movieName={movie.original_title}
/>
</React.Fragment>
))}
</Row>

{Loading &&
<div>Loading...</div>}

<br />
<div style={{ display: 'flex', justifyContent: 'center' }}>
<button ref={buttonRef} className="loadMore" onClick={loadMoreItems}>Load More</button>
</div>
</div>

</div>
)
}

export default LandingPage

0

김태진님의 프로필

김태진

질문자

2020.03.28

정말 감사합니다!!ㅎㅎ