본문 바로가기

항해99

[WIL] 그동안의 기록(2)

728x90

##Pagination( 백엔드에게 분할로 리스트를 받는 경우)

```List.js```
<ProductWrap>
        {product_list.map((p, idx) => {
          return <Product key={idx} {...p} />;
        })}
      </ProductWrap>
      <PageButtonWrap>
        <PageButtonUl>
          {[...Array(5)].map((n, index) => {
            return (
            <PageButtonli key={index} onClick={() => {
              dispatch(productActions.getProductDB(index + 1));
            }}>
              {index + 1}
              </PageButtonli>
            );
          })}
        </PageButtonUl>
 </PageButtonWrap>

<Product>는 컴포넌트로 리스트를 하나씩 받아주었습니다.  버튼 나열과 리스트 나열을 따로 설정해두었습니다.

 

 

##Pagination( 백엔드에게 통으로 리스트를 받는 경우)

const ProductList = () => {
  const dispatch = useDispatch();

  const [currentPage, setCurrentPage] = useState(1);
  const [postsPerPage, setPostsPerPage] = useState(20);
  const product_list = useSelector((state) => state.product.list);
  
  
  const indexOfLast = currentPage * postsPerPage;
  const indexOfFirst = parseInt(indexOfLast) - parseInt(postsPerPage);
  
  function currentPosts(tmp) {
    let currentPosts = 0;
    currentPosts = tmp.slice(indexOfFirst, indexOfLast);
    
    return currentPosts;
  }

  useEffect(() => {
    dispatch(productActions.getProductDB());
  }, []);

  return (
    <ListWrap>
      <ProdustsWrap>
        <Products posts={currentPosts(product_list)}></Products>
      </ProdustsWrap>
      <Pagination
        postsPerPage={postsPerPage}
        totalPosts={product_list.length}
        paginate={setCurrentPage}
      ></Pagination>
    </ListWrap>
  );
};
const Pagination = ({ postsPerPage, totalPosts, paginate }) => {
  const pageNumbers = [];
  for (let i = 1; i <= Math.ceil(totalPosts / postsPerPage); i++) {
    pageNumbers.push(i);
  }
  return (
    <PageWrap>
      <nav>
        <PageUl className="pagination">
          {pageNumbers.map((number) => (
            <PageLi
              key={number}
              className="page-item"
              onClick={() => paginate(number)}
            >
              <PageSpan className="page-link">{number}</PageSpan>
            </PageLi>
          ))}
        </PageUl>
      </nav>
    </PageWrap>
  );
};

리스트를 통으로 받아서 리스트를 설정할 때, 부모 컴퍼넌트에서 선언해놓은 set함수를 자식에게 넘겨줘서 값을 지정해줬습니다.

'항해99' 카테고리의 다른 글

[WIL] 8주차 항해 회고록  (0) 2022.03.06
[TIL] 항해 55일차  (0) 2022.03.05
[TIL]항해 45일, 그동안의 기록(1)  (0) 2022.02.24
[WIL] 6주차 항해 회고록  (0) 2022.02.20
[Computer Science] 9장 웹 브라우저  (0) 2022.02.18