쇼핑몰 & 장바구니

유관희·2022년 11월 10일
0

const Main = ({ products, setProducts}) => {
   // products는 json 안의 물건들이다. 
   const sortProduct = (type) => {
        const newProduct = [...products];
        if (type === 'recent') {
            newProduct.sort((a, b) => a.id - b.id);
            setProducts(newProduct);
        } else if (type === 'row') {
            newProduct.sort((a, b) => a.price - b.price);
            setProducts(newProduct);
        } else if (type === 'high') {
            newProduct.sort((a, b) => b.price - a.price);
            setProducts(newProduct);
        }
    };
 <div className={styles.filter}>
                <p onClick={() => sortProduct('recent')}>최신순</p>
                <p onClick={() => sortProduct('row')}>낮은 가격</p>
                <p onClick={() => sortProduct('high')}>높은 가격</p>
            </div>

Cart 안의 물건 지우는 방법

const handleRemove = (id) => {
        setCart(cart.filter((el) => el.id !== id));
       // 아이디를 받아 filter를 이용한다. 즉 필터 내용은 el.id 와 id 와 같지
       // 않은 것을 골라 setCart에 넣으라는 이런 식으로 지우려는 것만을 지우는 
       // 방식이 아니라 지우려는 것만을 제외하고 나머지를 받아오는 이런식으로 
       // 지우는 것이다. 
    };

checkbox 가 선택 되었는지 구현 방법

checked={checkLists.includes(cart.id) ? true : false}
체크 박스가 선택 구현은 include를 이용하는 것이다. checkbodx는 boolen 타입이라 true, false 만 받는다. 따라서 cart.id 가 checkList 안에 있으면 true, 없으면 false로 하여 ceckbox 의 선택 유무를 알 수 있다.

reduce를 이용한 총합 계산

const sum = found.map((item) => item[0].price * item[0].quantity);
const reducer = (acc, cur) => acc + cur
const itemTotal = sum.reduce(reducer);

map으로 돌린 item의 값을 한번에 구하는 방법으로서 일단 sum에 found의 값과 수량를 곱한 값을 넣는다. rudece를 정의한다. acc는 축적되는 값이고 cur은 더해 지는 값이다.
sum 값을 reduce를 이용해 itemTotal 값에 넣는다.

profile
안녕하세요~

0개의 댓글