REACT

[React] 함수형 컴포넌트에서 API 불러오기

yangjoy 2021. 8. 16. 22:42
import React from 'react';
import axios from 'axios';


function PortInfo({link, image, title, category}){
    return(
        <div className="port__item">
            <figure className="port__item__img">
                <a href={link}>
                    <img src={image} alt={title} />
                </a>
            </figure>
            <div className="port__item__txt">
                <h2>{title}</h2>
                <p>{category}</p>
            </div>
        </div>
    )
}

class Portfolio extends React.Component{
    state = {
        isLoading : true,
        ports : []//포트폴리오 내용을 저장할 곳
    }
    getPorts = async() =>{
        const {
            data : {
                data:{ports},
            }
        } = await axios.get("https://webstoryboy.github.io/dothome1/portfolio.json");
        // this.setState({isLoading : false, ports : ports}) 똑같으면 생략도 가능.
        this.setState({isLoading : false, ports})
    }
    //동기 비동기 차이점

    // 생명주기함수에서 파생된..
    componentDidMount(){
        setTimeout(() => {
            this.getPorts();
        },3000)
    }

    //사이트 로딩이 끝난후 componedidmount 실행, 그리고 render 실행

    render() {
        const{isLoading, ports} = this.state;
        //변수도 이렇게 설정할 수 도 있다. 구조분해할당
        return(
            <div>
                {isLoading ? (
                    <div>로딩중입니다...</div>
                ) : (
                    <div>
                        {ports.map((port) => (
                        <PortInfo
                            link={port.link}
                            image={port.image}
                            title={port.title}
                            category={port.category}
                        />
                        ))}    
                    </div>
                )}

            </div>
        )
    }
}

export default Portfolio;

'REACT' 카테고리의 다른 글

[React] axios(내용 추가하기)  (0) 2021.08.16
[React] map 응용2(portfolio)  (0) 2021.08.16
[React] map 응용하기  (0) 2021.08.16
[React] 클래스형 컴포넌트  (0) 2021.08.16
[React] map  (0) 2021.08.16