[Front-end] 수업 #070일 2-3

JooSehyun·2023년 2월 10일
0
post-thumbnail

React

함수형 컴포넌트 상태관리 JSON & AXIOS

🕵️‍♀️이번 수업은 함수형 컴포넌트에서 AXIOS를 가져와서 구현한다.

AXIOS 란?

Axiosnode.js와 브라우저를 위한 Promise 기반 HTTP 클라이언트 입니다. 그것은 동형 입니다(동일한 코드베이스로 브라우저와 node.js에서 실행할 수 있습니다). 서버 사이드에서는 네이티브 node.js의 http 모듈을 사용하고, 클라이언트(브라우저)에서는 XMLHttpRequests를 사용합니다.

AXIOS 사용준비

일단 AXIOS를 사용하기 위해 VsCode 터미널 창에서

  1. $ npm install axios를 입력하여 설치하거나
  2. <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> jsDelivr CDN 사용하기가 있다. 둘중에 마음에 드는걸로 선택하여 준비를 한다.

👼 자세한 AXIOS 에 관한 내용은 [튜토리얼] 시리즈에 써볼 생각이다.

우선 사용준비는 끝났고 폴더의 추가가 필요하다. Data 파일이 있다는 가정하에 짧은 멤버 정보들을 JSON 를 만들어 볼 생각이다.

데이터를 만들 폴더 경로는 아래와 같다.

  • index.html
  • js 폴더
    • script.js
  • css 폴더
    • style.css
  • data 폴더 👈 이렇게 만들어 두었고
    • member.json 👈 여기에 json 파일을 만들었다.

data 폴더 => member.json

{
    "addr":[
        {"이름":"가ㅇㅇ","거주지":"화성","취미":["잠자기","먹기"]},
        {"이름":"나ㅇㅇ","거주지":"평택","취미":["독서","영화보기"]},
        {"이름":"다ㅇㅇ","거주지":"시흥","취미":["영화보기","맛집가기"]},
        {"이름":"라ㅇㅇ","거주지":"시흥","취미":["등산","영화보기"]},
        {"이름":"마ㅇㅇ","거주지":"화성","취미":["수영","독서","등산"]},
        {"이름":"바ㅇㅇ","거주지":"오산","취미":["등산","맛집가기"]},
        {"이름":"사ㅇㅇ","거주지":"종로","취미":["잠자기","음악"]}
    ],
    "성적표":[
        {"이름":"가ㅇㅇ","국어":100,"영어":100,"수학":100},
        {"이름":"나ㅇㅇ","국어":100,"영어":100,"수학":100},
        {"이름":"다ㅇㅇ","국어":100,"영어":100,"수학":100},
        {"이름":"라ㅇㅇ","국어":100,"영어":100,"수학":100},
        {"이름":"마ㅇㅇ","국어":100,"영어":100,"수학":100},
        {"이름":"바ㅇㅇ","국어":100,"영어":100,"수학":100},
        {"이름":"사ㅇㅇ","국어":100,"영어":100,"수학":100}
    ],
    "주소록":[
        {"이름":"가ㅇㅇ","주소":"서울시 강남구", "전화":"010-1234-1234"},
        {"이름":"나ㅇㅇ","주소":"서울시 강남구", "전화":"010-1234-1234"},
        {"이름":"다ㅇㅇ","주소":"서울시 강남구", "전화":"010-1234-1234"},
        {"이름":"라ㅇㅇ","주소":"서울시 강남구", "전화":"010-1234-1234"},
        {"이름":"마ㅇㅇ","주소":"서울시 강남구", "전화":"010-1234-1234"},
        {"이름":"바ㅇㅇ","주소":"서울시 강남구", "전화":"010-1234-1234"},
        {"이름":"사ㅇㅇ","주소":"서울시 강남구", "전화":"010-1234-1234"}
    ]
}

👩‍🚀 JSON 문법은 아래와 같이 쌍따옴표 ""로 사용한다.

1. 틀린예시: {이름:'가가가',거주지:'목성',취미:['우주여행','감자심기']}
2. 올바른예시: {"이름":"가가가","거주지":"목성","취미":["우주여행","감자심기"]}

ex) 올바른 예시

{
	"people" : [
    { "firstName" : "나까" , "lastName" : "다" },
    { "firstName" : "홍남" , "lastName" : "김" },
    { "firstName" : "건욱" , "lastName" : "김" }
	]
}

먼저 전체 코드 부터 보자

👨‍💻전체 코드 구성은 위와 같고 하나하나 코드를 복습을 해나가면서 작성한다.

전체코드

(()=>{
    const MemberComponent = (props) => {
        const [addr, setAddr]=React.useState([]);
        React.useEffect(()=>{
        const axiosResult=axios.get('./data/member.json')
            .then((Response)=>{
                return(setAddr([...Response.data.addr])
                )
            })
            .catch((Error)=>{
                return(console.log(`AXIOS 실패:${Error}`))
            });
            console.log(addr);
        },[]);
        console.log(addr); 
        return (
            <div id="wrap">
                <h1 style={style.h1}>{props.title}</h1>
                <AddressComponent title2={props.title2} addr={props.addr}/>
            </div>
        );
    };
    const AddressComponent = (props) => {
        const result=props.addr.map(function(item, index, array){
            return(
                <tr>
                    <td>{index+1}</td>
                    <td>{item.이름}</td>
                    <td>{item.거주지}</td>
                    <td>
                        {item.취미.map(function(item2,index2){
                            return(
                                <span>
                                    <a href="#" title={item2}>{item2}</a>
                                    {(item.취미.length-1)==index2? '':' , '}
                                </span>
                            );
                        })}
                    </td>
                </tr>
            );
        })
        return (
            <div id="address">
                <h2 style={style.h2}>{props.title2}</h2>
                <table>
                    <thead>
                        <tr>
                            <th>번호</th>
                            <th>이름</th>
                            <th>거주지</th>
                            <th>취미</th>
                        </tr>
                    </thead>
                    <tbody>
                        {result}
                    </tbody>
                </table>
            </div>
        );
    };
    const style={
        h1:{
            fontSize:'36px',
            color:'#c66',
            textAlign:'center',
            padding:'50px 0'
        },
        h2:{
            fontSize:'30px',
            color:'#66c',
            textAlign:'center',
            padding:'30px 0'
        }
    }
    MemberComponent.defaultProps={
        title:'회원관리',
        title2:'ADDRESS',
        section1(){
            return(
                console.log('메서드 리턴값!!')
            );
        },
        addr:[
            {이름:'가ㅇㅇ',거주지:'화성',취미:['잠자기','먹기']},
            {이름:'나ㅇㅇ',거주지:'평택',취미:['독서','영화보기']},
            {이름:'다ㅇㅇ',거주지:'시흥',취미:['영화보기','맛집가기']},
            {이름:'라ㅇㅇ',거주지:'시흥',취미:['등산','영화보기']},
            {이름:'마ㅇㅇ',거주지:'화성',취미:['수영','독서','등산']},
            {이름:'바ㅇㅇ',거주지:'오산',취미:['등산','맛집가기']},
            {이름:'사ㅇㅇ',거주지:'종로',취미:['잠자기','음악']}
        ]
    }
    ReactDOM.render(
        <MemberComponent/>,
        document.getElementById('root')
    )
})()

MemberComponent (최상위 컴포넌트)

const MemberComponent = (props) => {
        const [addr, setAddr]=React.useState([]);
        React.useEffect(()=>{
        const axiosResult=axios.get('./data/member.json')
            .then((Response)=>{
                return(setAddr([...Response.data.addr])
                )
            })
            .catch((Error)=>{
                return(console.log(`AXIOS 실패:${Error}`))
            });
            console.log(addr);
        },[]);
        console.log(addr); 
        return (
            <div id="wrap">
                <h1 style={style.h1}>{props.title}</h1>
                <AddressComponent title2={props.title2} addr={props.addr}/>
            </div>
        );
    };

함수형 컴포넌트로 MemberComponent 를 만든다. statesetState는 각 addrsetAddr로 만들고 useState의 초기값은 ([]) 빈 배열값을 초기값으로 둔다.

React.useEffect(()=>{
	const axiosResult=axios.get('./data/member.json')
    .then((Response)=>{
    	return(setAddr([...Response.data.addr]))
    })
    .catch((Error))=>{
    	return(console.log(`AXIOS 실패:${Error}`))
    })
    console.log(addr);
},[]);

useEffect로 const변수로 axiosResult를 만들었다. axios.get('./data/member.json') 👈 (member의 json을 만든곳의 경로)를 써주고
비동기 처리를 위해 then , catch를 쓴다.

then에서는 가져오기에 성공했다면 응답메세지 Response를 읽고 return문에
setAddr([...Response.data.addr])을 담는다.
가져오기에 실패했다면 catch문에 Error를 담고 return문에 (console.log(`AXIOS 실패:${Error}`))를 담는다.
useEffectget , then , catch를 불러주고 마지막은 한번만 실행되게 하기위해 ,[] 를 써주면 한번만 실행된다.

	return (
            <div id="wrap">
                <h1 style={style.h1}>{props.title}</h1>
                <AddressComponent title2={props.title2} addr={props.addr}/>
            </div>
        );
    };

다음 코드는 화면에 보일 return문이다. wrap으로 감싼 div가 있고 안에는 구조 분해 할당으로 만든 스타일이 지정되었고 MemberComponentdefaultProps 값을 넣어주었다.
👇 전체코드를 보면 이렇게 초기값props를 지정한 곳이 있다.

MemberComponent.defaultProps={
        title:'회원관리',

props.title을 넣어주었고, 하위 컴포넌트인 AddressComponent가 들어가 있고 props를 전달하기 위해 <AddressComponent title2={props.title2} addr={props.addr}/> 로 작성하여 props를 전달한다.


AddressComponent

const AddressComponent = (props) => {
        const result=props.addr.map(function(item, index, array){
            /* console.log(item); */
            return(
                <tr>
                    <td>{index+1}</td>
                    <td>{item.이름}</td>
                    <td>{item.거주지}</td>
                    <td>
                        {item.취미.map(function(item2,index2){
                            return(
                                <span>
                                    <a href="#" title={item2}>{item2}</a>
                                    {(item.취미.length-1)==index2? '':' , '}
                                </span>
                            );
                        })}
                    </td>
                </tr>
            );
        })
        return (
            <div id="address">
                <h2 style={style.h2}>{props.title2}</h2>
                <table>
                    <thead>
                        <tr>
                            <th>번호</th>
                            <th>이름</th>
                            <th>거주지</th>
                            <th>취미</th>
                        </tr>
                    </thead>
                    <tbody>
                        {result}
                    </tbody>
                </table>
            </div>
        );
    };

AddressComponent 의 코드이다. props 를 전달받고 result의 변수를 만들고 props.addr.map를 담는다.
map 안에 함수에 매개변수 item , index , array를 담고 리턴문을 만드는데

return(
                <tr>
                    <td>{index+1}</td>
                    <td>{item.이름}</td>
                    <td>{item.거주지}</td>
                    <td>
                        {item.취미.map(function(item2,index2){
                            return(
                                <span>
                                    <a href="#" title={item2}>{item2}</a>
                                    {(item.취미.length-1)==index2? '':' , '}
                                </span>
                            );
                        })}
                    </td>
                </tr>
            );
return (
            <div id="address">
                <h2 style={style.h2}>{props.title2}</h2>
                <table>
                    <thead>
                        <tr>
                            <th>번호</th>
                            <th>이름</th>
                            <th>거주지</th>
                            <th>취미</th>
                        </tr>
                    </thead>
                    <tbody>
                        {result}
                    </tbody>
                </table>
            </div>
         );

리턴문을 만들어서 이렇게 테이블화 시켜준다.


0개의 댓글