본문 바로가기

react

리액트 _16_React_useState, useEffect

1. public 밑에 music.json을 붙여넣는다.

music.json
0.01MB

2. index.html에 css를 넣는다.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

클래스로 container 도 적어준다.

3. 파일을 가져와야 하기 때문에 package.json에 axios를 import 해준다.

4. App2.js에다가  music.json에 있는 값을 get으로 가져온다. 

* let은 완전한 지역변수를 만들어줄 때 사용한다. 딱 속해있는 function 안에서만 사용할 수 있다.

import React from "react";
import axios from "axios";

function App2() {

    let music=[];
    axios.get('http://localhost:3000/music.json').then((res)=>{
        music=res.data;
    })
    console.log(music)
    return(
        <div className={"row"}>

        </div>
    )
}

export default App2;

 

5. index.js에서 App2가 실행되게 적는다.

결과) 변수로 array를 못 받아 오는 것을 확인할 수 있다. 

값을 받으려면 useState를 이용해야한다. 

<문법>

const [변수명, 메소드]=useState("[]") ("{}") ("0") (false)
[music,setMusic]

6. set메소드를 이용해서 코드를 작성한다.

결과) 데이터가 들어와있는 것을 확인 할 수 있다. 

7. 그냥 axios로 가져오면 무한루프 돌기 때문에 useEffect를 이용해서 시작할 때 딱 한번만 불러오게 작성해야한다. 

* 뒤에 deps[]는 실행 할 때 한번만 나오게 하는 것이다. componentDidMount를 사용할 때 deps를 붙인다.  

  componentDidUpdate는 뒤에 deps를 빼야한다.

<문법>
==========================
componentDidMount

useEffect(()=>{
    처리 => 데이터읽기 axios,fetch..을 사용
})

==========================
componentDidUpdate

useEffect(()=>{
    처리 => 데이터읽기 axios,fetch..을 사용
},deps:[])
 useEffect(()=>{
        axios.get('http://localhost:3000/music.json').then((res)=>{
            setMusic(res.data);
            console.log(res.data)
        })
    },deps:[])

루프가 한번만 돌아갔음

8. render 부분을 작성해보자.

   const html 변수를 만든다.

    const html=music.map((m)=>
        <tr>
            <td>{m.rank}</td>
            <td></td>
            <td><img src={m.poster} width={"35"} height={"35"}/></td>
            <td>{m.title}</td>
            <td>{m.singer}</td>
        </tr>
   )

9. return 부분에 html을 넣어준다. 

return(
        <div className={"row"}>
            <table className={"table"}>
                <thead>
                    <tr className={"success"}>
                        <td>순위</td>
                        <td>등폭</td>
                        <td></td>
                        <td>노래명</td>
                        <td>가수명</td>
                    </tr>
                </thead>
                <tbody>
                    {html}
                </tbody>
            </table>
        </div>
    )

 

10. 상승 하강 유지를 표시해 주기 위해 다중if문을 이용한다. 

const html=music.map((m)=>
        <tr>
            <td>{m.rank}</td>
            <td>
                {
                    m.state==="상승" &&
                        <span style={{"color":"red"}}>▲{m.idcrement}</span>
                }
                {
                    m.state==="하강" &&
                    <span style={{"color":"blue"}}>▼{m.idcrement}</span>
                }
                {
                    m.state==="유지" &&
                    <span style={{"color":"grey"}}>-</span>
                }
            </td>
            <td><img src={m.poster} width={"35"} height={"35"}/></td>
            <td>{m.title}</td>
            <td>{m.singer}</td>
        </tr>
    );

11. 위에 크게 Music Top50 가 출력되게 function을 만든다. 

 

방법1)

function H() {
    return(
        <h1 className={"text-center"}>Music Top50</h1>
    )
}

방법2)

const H2= function(){
    return(
        <h1 className={"text-center"}>Music Top50</h1>
    )
}

방법3)

const H= () =>{
    return(
        <h1 className={"text-center"}>Music Top50</h1>
    )
}

호출 방법은 동일하게 <> 태그 안에 H를 넣으면 된다. 

결과) 

+App2.js 전체코드)

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

/*const [변수명, 메소드]=useState("[]") ("{}") ("0") (false)
[music,setMusic]*/

function App2() {

    const [music,setMusic]= useState([]);
    useEffect(()=>{
        axios.get('http://localhost:3000/music.json').then((res)=>{
            setMusic(res.data);
            console.log(res.data)
        })
    },[])

    const html=music.map((m)=>
        <tr>
            <td>{m.rank}</td>
            <td>
                {
                    m.state==="상승" &&
                        <span style={{"color":"red"}}>▲{m.idcrement}</span>
                }
                {
                    m.state==="하강" &&
                    <span style={{"color":"blue"}}>▼{m.idcrement}</span>
                }
                {
                    m.state==="유지" &&
                    <span style={{"color":"grey"}}>-</span>
                }
            </td>
            <td><img src={m.poster} width={"35"} height={"35"}/></td>
            <td>{m.title}</td>
            <td>{m.singer}</td>
        </tr>
    );

    return(
        <div className={"row"}>
            <H/>
            <table className={"table"}>
                <thead>
                    <tr className={"success"}>
                        <td>순위</td>
                        <td>등폭</td>
                        <td></td>
                        <td>노래명</td>
                        <td>가수명</td>
                    </tr>
                </thead>
                <tbody>
                    {html}
                </tbody>
            </table>
        </div>
    )

}
/*const H= () =>{
    return(
        <h1 className={"text-center"}>Music Top50</h1>
    )
}

const H2= function(){
    return(
        <h1 className={"text-center"}>Music Top50</h1>
    )
}*/

function H() {
    return(
        <h1 className={"text-center"}>Music Top50</h1>
    )
}

export default App2;

 

+)  제목 색깔 랜덤으로 변하게 하기

-- color라는 변수를 만들고 parseInt(Math.random)을 이용해서 새로고침할 때마다 색이 변하게 한다. 

const H= () =>{
    const color =["red","orange","pink","yellow","blue"];
    const no=parseInt(Math.random()*5); //random(0.0~0.99)
    return(
        <h1 className={"text-center"} style={{"color":color[no]}}>Music Top50</h1>
    )
}

결과 =======

 

반응형

'react' 카테고리의 다른 글

리액트_webStrom git 연동하기  (0) 2020.05.23
리액트 공부할 때 참고자료  (0) 2020.05.23
리액트 _15_React_prop 사용법_2  (0) 2020.05.23
리액트 _14_React_prop 사용법  (0) 2020.05.23
리액트 _13_React & Redux 특징  (0) 2020.05.23