IT/웹프로그래밍

react로 json 데이터 불러오기

thesse 2019. 8. 14. 20:37
300x250
반응형

index.js

새로 만들 파일의 이름은 Allview.js이다.

App.js가 임포트되어있던 것을 Allview로 바꾸고

render 안의 태그도 Allview로 바꿔준다.

 

 

 

Allview.js

import React, {useEffect, useState} from 'react';
import * as $ from 'jquery';

function Allview() {
    const [ exams, setExams ] = useState(null);

        $.ajax({
            url:"http://(서버주소)/AllviewDB_view.jsp",	//클라이언트가 요청을 보낼 서버의 url 주소
            type: "GET",			//http 요청 방식 (get, post)
        })
        
        //http 요청이 성공하면 요청한 데이터가 done() 메소드로 전달됨.
        .done(function(json){
            console.log("done");
            console.log(json);
            setExams(json.ret);
        })
        
        //http 요청이 실패하면 오류와 상태에 관한 정보가 fail() 메소드로 전달됨
        .fail(function(xhr, status, errorThrown){
            console.log("fail");
            console.log(xhr, status, errorThrown);
        })
        
        //http 요청이 성공하거나 실패하거나 상관없이 언제나 always() 메소드가 실행됨
        .always(function(xhr, status){
            console.log("always");
            console.log(xhr, status);
        });

  return (
    <div className="App">
            <table className="table">
                <thead>
                    <tr>
                        <th scope="col">이름</th>
                        <th scope="col">학번</th>
                        <th scope="col">국어</th>
                        <th scope="col">영어</th>
                        <th scope="col">수학</th>
                        <th scope="col">총점</th>
                        <th scope="col">평균</th>
                    </tr>
                </thead>
                <tbody>
                    {exams && exams.map((item) =>   //exams가 null이 아닐때, exams가 하나씩 들어가면서 루프 돌림
                        <tr key={item.studentid}>
                            <td>{item.name}</td>
                            <td>{item.studentid}</td>
                            <td>{item.kor}</td>
                            <td>{item.eng}</td>
                            <td>{item.mat}</td>
                            <td>{item.tot}</td>
                            <td>{item.avg}</td>
                        </tr>)}
                </tbody>
            </table>
    </div>
  );
}

export default Allview;

위 코드를 실행하면 아래와 같은 화면이 뜬다.

AllviewDB_view.jsp 파일은 DB에서 값을 받아와 json 형태로 출력하는 파일이다.

Allview.js는 해당 json 데이터를 ajax로 받아와 테이블에 뿌려주는 것이다.

 

 

위 코드 중 const [ exams, setExams ] = useState(null); 이 부분에서

앞쪽의 exams는 State, 뒤쪽의 setExams는 State를 갱신하는 함수 이름이다.

우변의 useState(null)은 초기값으로 null을 지정해준 것이다.

(이를 위해서 첫번째 줄에 useState를 임포트해주어야 한다.)

 

리액트에서는 State가 중요하다고 한다.

상태(State)가 바뀌면 렌더링을 다시 하여 화면을 갱신시켜준다.

싱글페이지이기는 하지만, 사용자가 느끼기에는 바뀌는것처럼 느껴져야 한다는 것이다.

 

 

 

 

 

그런데 위와 같은 코드에서는 ajax가 서버에 리퀘스트를 계속해서 보내고 있다.

연결에 성공해서 리스폰스를 받아올 때마다 콘솔에 로그를 찍게 하고 있는데,

위 코드를 그대로 실행하면 일초에도 여러 개의 로그가 찍히는 것이 보인다.

아래 코드는 한번 리스폰스를 받아온 후, 버튼을 누를 때만 업데이트하게 바꾼 것이다.

Allview.js 변경

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

function Allview() {

    async function fetchData(){
        const response = await fetch(url)
        response.text()
        .then((value)=>{
            setExams(JSON.parse(value).ret);
            console.log(exams);
        });
    }

    const [ exams, setExams ] = useState(null);
    const url = "http://(서버주소)/AllviewDB_view.jsp";
    
    useEffect(() => {
        fetchData();

    }, [url]);  //,[url] 이거 없으면 리퀘스트 계---속 보냄

  return (
    <div className="App">
            <table className="table">
               
               (...중략...)
               
            </table>
            <button onClick={()=>fetchData()}>refresh</button>
    </div>
  );
}

export default Allview;

제이쿼리를 걷어내서  import * as $ from 'jquery'; 부분이 가 빠졌다.

useEffect에서 $.ajax(~) 부분이 지워지고 async function fetchData()가 생겼다.

 

return 부분에서는 하단에 버튼이 생겨 onClick 이벤트로 fetchData()를 걸었다.

변형된 코드에서는 리퀘스트가 상시 요청되지 않고, 버튼을 눌렀을 때만 요청된다.

 

300x250
반응형