Stack/React

[React] Lamp 쇼핑몰 구현하기 3 (서버에 연결하기)

7ingout 2022. 7. 1. 11:14

1.

LAMP-SHOPPING-CLIENT

main/index.js 에서 상품 불러오는거 따로 뗀 후 MainProduct라는 새 파일 만든 후 붙여준다 !

main/index.js

요로코롬

main/MainProduct.js

이걸로 바꾸기 

import React from 'react';
import { Link } from 'react-router-dom'

const MainProduct = ( {product} ) => {
    return (
        <div className="product-card">
            <Link to={`/product/${product.id}`}>
            <div className='product-img'>
                <img src={product.imgageUrl} alt="" />
            </div>
            <div className='product-contents'>
                <span className='product-name'>{product.name}</span>
                <span className='product-price'>{product.price}</span>
                <div className='product-seller'>
                <img src="images/icons/avatar.png" alt=""/>{product.seller}
                </div>
            </div>
            </Link>
        </div>
    );
};

export default MainProduct;

 

2.

LAMP-SHOPPING-SERVER

server.js 로 가서 추가하기

// method는 get이고 오고 url은 /product/2 로 요청이 온 경우
app.get('/product/:id', async (req, res) => {
    const params = req.params;
    const { id } = params;
    const product = {
        id: id,
        name: "서버에서 보내는 이름",
        price: 50000,
        imgsrc:"images/products/product4.jpg",
        seller: "green",
    }
    res.send(product);
});

 

3.

LAMP-SHOPPING-CLIENT

App.js 에서 /products 되어 있던 것을 요렇게 바꿔준다

 

4.

LAMP-SHOPPING-CLIENT

main/MainProduct.js로 가서 import { Link } from 'react-router-dom' 선언 후 Link로 감싸준다

상품을 누르게 되면 상품 자세히 보기 페이지로 넘어가게 된다 ~

 

5. product/index.js

import React, { useState, useEffect } from 'react';
import axios from 'axios';

import { useParams } from 'react-router-dom';   // id 받아오기 위해서

선언하기

main/MainProduct.js 에서 받아오는 product.id를 produt/index.js 에서 useParams()를 이용해 받아올 것이다

 

product/index.js

import React, { useState, useEffect } from 'react';
import "./product.scss"
import axios from 'axios';
import { useParams } from 'react-router-dom';

const ProductPage = (props) => {
    const [ product, setProduct ] = useState(null);
    // useParams() 실행되면 파라미터 값을 가지고 있는 객체를 반환
    // product/1
    const { id } = useParams();
    useEffect(function(){
        axios.get(`http://localhost:3000/product/${id}`)
        .then(result=> {
            console.log(result);
            const data = result.data;
            setProduct(data);
        })
        .catch(e=> {
            console.log(e);
        })
    }, []) // 빈 배열 넣어줘야 마운트 될 때 한번만 시행
    if(!product) return <div>로딩중입니다...</div>
    return (
        <div className='inner'>
            <div id="image-box">
                <img src={product.imageUrl} alt =""/>
            </div>
            <div id="profile-box">
                <ul>
                    <li>
                        <div>
                            <img src="/images/icons/avatar.png" alt=""/>
                            <span>{product.seller}</span>
                        </div>
                    </li>
                    <li>
                    {product.name}
                    </li>
                    <li>
                        가격 {product.price}
                    </li>
                    <li>등록일 2022년 6월 2일</li>
                    <li>상세설명</li>
                </ul>
            </div>
        </div>
    );
};

export default ProductPage;

------- 사실 우리는 데이터를 데이터베이스에서 받아온다, 서버에서 그냥 해본거 -------