본문 바로가기

react-shop-web/front & back

데이터베이스에서 가져온 상품 정보들을 화면에서 보여주기

표를 만들어주기 위해 새로운 컴포넌트를 만들자.

CartPage 폴더에서 Sections 폴더를 만들고 UserCarBlcok.js 와 css 파일을 만든다.

 

더보기
import React, {useEffect} from 'react'
import {useDispatch} from 'react-redux';
import {getCartItems} from '../../../_actions/user_actions';
import UserCardBlock from './Sections/UserCardBlock';

function CartPage(props) {
  const dispatch = useDispatch();

  useEffect(() => {

    let cartItems = []
    
    // 리덕스 user state에서 cart안에 상품이 들어있는지 확인 
    if(props.user.userData && props.user.userData.cart) {
      // 카트 안에 상품이 하나 이상 들어있다면 
      if(props.user.userData.cart.length > 0){
        props.user.userData.cart.forEach(item => {
          cartItems.push(item.id)
        })

        // 밑에 액션에 매개변수로 방금 props로부터 받은 user의 userData에서 cart들을 담은 변수와,
        // userData의 cart 정보도 주자. (이때 두번째 매개변수를 넣어주는 이유는 quantity는 user의 cart 부분에만 존재하기 때문)
        dispatch(getCartItems(cartItems, props.user.userData.cart))
      }
    }
  
    return () => {
      
    }
  }, [props.user.userData])
  
  return (
    <div style={{ width: '85%', margin: '3rem auto'}}>
      <h1>My Cart</h1>
      {/* 밑에 props 주는 과정에서도 
      페이지가 렌더링 될 때는 return값을 먼저 렌더링되고 그 후에 props에 값이 들어올 때도 있다. 이때도 useEffect의
      빈칸에 props.user.userData를 넣어주지 않으면 useEffect 안에 있는 조건문이 통과되지 않기 때문에 cartItems에는 아무것도 담기지 않는다.
      UserCardBlock 컴포넌트에 props를 줄 때도 현재 컴포넌트 props에 값이 담겨있을 때를 조건으로 줘야 오류가 나지 않는다. */}
      <UserCardBlock products={props.user.cartDetail && props.user.cartDetail.product}/>  
    </div>
  )
}

export default CartPage

CartPage.js

 

 

 

더보기
import React from 'react'
import "./UserCardBlock.css"

function UserCardBlock(props) {
  
  const renderCartImage = (images) => {
    if(images.length > 0) {
      let image = images[0] 
      return `${process.env.REACT_APP_SERVER}/${image}`
    }
  }

  const renderItems = () => (
    props.products && props.products.map((product, index) => (
      <tr key={index}>
        <td>
          <img style={{width:'70px'}} alt="product"
          src={renderCartImage(product.images)} />
        </td>
        <td>
          {product.quantity} EA
        </td>
        <td>
          $ {product.price}
        </td>
        <td>
          <button>
            Remove
          </button>
        </td>
      </tr>
    ))
  )

  return (
    <div>
      <table>
        <thead>
          <tr>
            <th>Product Image</th>
            <th>Product Quantity</th>
            <th>Product Price</th>
            <th>Remove From Cart</th>
          </tr>
        </thead> 
        <tbody>
          {renderItems()}
        </tbody>
      </table>
    </div>
  )
}

export default UserCardBlock

UserCardBlcok.js

 

 

더보기
table {
    font-family: arial, sans-serif;
    border-collapse: collapse;
    width: 100%;
}

td,th {
    border: 1px solid #dddddd;
    text-align: left;
    padding: 8px;
}

tr:nth-child(even) {
    background-color: #dddddd;
}

UserCardBlock.css