원하는 데이터를 테이블로 만들고 이를 페이지 선택하고자 했다.
const Table = memo(({children, ...props}: any) => {
return <StyledTable>{children}</StyledTable>;
});
export default Table;
props의 변화가 없을 때
2-2. 클래스 기반 함수에는 사용하지말자.
//list.tsx
const MyList = () => {
const [posts, setPosts] = useState([]);
const [curPage, setCurPage] = useState(1);
const [postPerPage] = useState(10);
const getGames = async () => {
await axios.get('http://localhost:4000/data')
.then(res => {
setPosts(res.data)
})
.catch(error => {
console.error()
})
};
useEffect(() => {
getGames();
}, []);
const indexOfLastPost = curPage * postPerPage // 1*10 = 10번 포스트
const indexOfFirstPost = indexOfLastPost - postPerPage // 10-10 = 0번 포스트
const curPosts = posts.slice(indexOfFirstPost, indexOfLastPost);
const Paginate = (pageNum: any) => setCurPage(pageNum);
Paginate와 pageNum은 다른 컴퍼넌트에서 가져오기에 아래에서 다룬다.
return(
<>
<div>
{curPosts.map((res: {id: any, name: any}) => {
return(
<div>{res.name}</div>
)
</div>
<Pagination
postPerPage = {postPerPage}
tatalPerPage = {posts.length}
pagination = {Pagination} />
</>
//list.tsx 끝
//pagination.tsx
const Pagination = ({postPerPage, totalPosts, paginate}: any) => {
const pageNumbers = [];
for (let i = 1; 1 <= Math.ceil(totalPosts / postPerPage); i++) {
pageNumbers.push(i);
<nav>
<ul>
{pageNumbers.map(num => <li><a onClick={() => paginate(num) href="#!">{num}</a></li>)}
</ul>
</nav>