🌐 Web/Redux

03. Redux를 이용한 애플리케이션 : store 생성

dlalwl_jpg 2022. 9. 3. 19:41

검색엔진에 redux cdn을 검색하여 홈페이지에 들어가면 redux를 서버에 설치하지 않고, 그냥 복사하여 사용할 수 있는 페이지가 나온다. 

여기서 맨 아래 주소를 카피한다. 

그리고 public 폴더에 with-redux.html 파일을 만들고 다음과 같이 주소를 넣어준다.

<!DOCTYPE html>
<html>
    <head>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.2.0/redux.js"></script>
    </head>
    <body>

    </body>
</html>

그리고 without-redux.html에서 작성한 <body>부분을 복붙해주고 red만 남기고 지워준다.

<!DOCTYPE html>
<html>
    <body>
        <style>
            .container{
                border:5px solid black;
                padding:10px;
            }
        </style>
        <dix id="red"></dix>
        <script>
function red(){
    document.querySelector('#red').innerHTML = `
        <div class="container" id="component_red">
            <h1>red</h1>
            <input type="button" value="fire" onclick="
            document.querySelector('#component_red').style.backgroundColor = 'red';
            document.querySelector('#component_green').style.backgroundColor = 'red';
            document.querySelector('#component_blue').style.backgroundColor = 'red';
            ">
        </div>
    `;
}
red();
        </script>
    </body>

</html>

이제 red부분을 redux에 의해 동작하도록 변경할 것이다.


redux를 이용한다는 것은 store를 만들어 state의 상태를 바꾸는 것이 redux의 핵심이다.

따라서 첫 번째로 해야할 것은 store를 만들어 state가 생성하고,

reducer라는 함수를 만들어 store에 주입하는 것이 첫 번째로 할 일이다.

state는 store를 만들면 자동으로 생성된다.

reducer가 하는 역할은 dispatch에 의해 action이 들어오게 되면

reducer가 그 action 값과 기존에 있었던 state의 값을 참조해서 새로운 state값을 만들어준다. 

은행으로 치면 dispatch가 창구직원, reducer가 은행장부에 누가 어떤 것을 했는지 적는 사람, state가 장부라고 할 수 있다.

<!DOCTYPE html>
<html>
    <head>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.2.0/redux.js"></script>
    </head>
    <body>
        <style>
            .container{
                border:5px solid black;
                padding:10px;
            }
        </style>
        <dix id="red"></dix>
        <script>       
            //reducer는 기존의 state값과 action값을 받아야 해서 인자를 state, action 두 가지를 작성해야 한다.
            function reducer(state, action){
                if(state === undefined){ //state의 값이 정의되지 않았다는 것은 초기값이라는 의미
                    return {color:'yellow'} //초기값 리턴
                }
            }
            //복붙한 주소에 의해 redux객체가 생성됨
            //createStore 입력값으로 reducer라는 것이 들어가야 한다.     
           var store = Redux.createStore(reducer); //store가 'store'라는 전역변수에 저장하여 애플리케이션 어디서든 실행 가능하도록 한다.
           
            console.log(store.getState()); //state값이 잘 저장 되었는지 확인할 때 getstate를 사용한다.
function red(){
    //red의 기본적인 css 색깔을 위에서 설정한 초기값 색깔로 지정한다.
    var state = store.getState();
    document.querySelector('#red').innerHTML = `
        <div class="container" id="component_red" style="background-color:${state.color}"> 
            <h1>red</h1>
            <input type="button" value="fire" onclick="
            document.querySelector('#component_red').style.backgroundColor = 'red';
            document.querySelector('#component_green').style.backgroundColor = 'red';
            document.querySelector('#component_blue').style.backgroundColor = 'red';
            ">
        </div>
    `;
}
red();
        </script>
    </body>
</html>

위와 같이 코드를 작성해보면 red의 기본값 색깔이 지정된다.

18행의 yellow를 red로 바꾸면 빨간색으로 초기값이 설정된다.


정리하자면, 우리가 store를 만들면 내부적으로 state의 값이 생성된다. 

이 state의 값을 가져올 때는 getState를 사용해야 한다.

그리고 reducer를 통해 state의 값을 만들어줘야 하는데 그때 reducer의 기존 state의 값이 undefined라면 그것은 초기화를 위해 최초로 실행되는 reducer에 대한 호출이기 때문에 원하는 초기값을 return 해주면 redux의 store에는 그 초기값이 지정된다.

 

강의 영상 - https://youtu.be/8EhmwDKSeJQ