🌐 Web/Redux

04. Redux를 이용한 애플리케이션 : reducer와 action을 이용해서 새로운 state 값 만들기

dlalwl_jpg 2022. 9. 3. 19:42

이번에는 state의 값을 변경하는 방법에 대해 알아보자.

state를 변경하기 위해서는 action이라는 것을 만들고 dispatch에게 제출하면 dispatch가 reducer라는 것을 호출한다.

그때 이전의 state 값과 action의 값을 동시에 준다. 그러면 우리가 짤 reducer 함수가 그것을 분석해 state의 최종적인 값을 return 해준다.


with-redux.html

<!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){
                console.log(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="
            
                store.dispatch({type:'CHANGE_COLOR', COLOR:'red'}); //store에 dispatch 함수를 호출할 때 type 객체를 주는데 이것을 반드시 있어야 한다.
            ">
        </div>
    `;
}
red();
        </script>
    </body>
</html>

위에서 작성한 코드를 통해

처음에 설명한 dispatch가 reducer 함수를 호출하고, 이전의 state값과 action 값을 동시에 주는 것을 확인해보자.

홈페이지에서 개발자도구 - console로 가서 fire 버튼을 클릭하면

이전의 state 값인 yellow와 action 값인 type값이 나타나는 것을 확인할 수 있다.

다시 말하면 reducer 라는 것은 이전의 state와 action을 받아서 다음의 state 값을 return 해준다.


state값 바꾸는 방법

redux를 사용할 때 여러 효용들을 최대한 활용하기 위해 state값을 변경해 그것을 return하지 말고,

state값을 복제하고, 복제된 복사본을 변경한 다음 그것을 return 해준다.

복제를 할 때는 Object.assign()을 사용한다. 이때 첫 번째 인자로는 반드시 빈 객체를 준다.

예를 들어, Object.assign({}, {name: 'egoing'}, {city: 'seoul'}); 이라는 코드는 첫 번째 인자에 두 번째 인자를 복사하고, 그 결과에 다시 세 번째를 인자를 복사한다.

왜냐하면 Object.assign()의 return 값은 첫 번째 인자인 객체이기 때문이다.

reducer가 실행될 때마다 return되는 값이 새로운 state값이 되는데 각각의 state값들이 서로 완전히 독립된 복제된 결과들이 return 되어야 한다.

이것을 참고하여 yellow 값을 red로 변경해보자.

with-redux.html

<!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){
                console.log(state, action);
                if(state === undefined){ //state의 값이 정의되지 않았다는 것은 초기값이라는 의미
                    return {color:'yellow'} //초기값 리턴
                }

                var newState;

                if(action.type === 'CHANGE_COLOR'){
                    newState = Object.assign({}, state, {color:'red'}); //state 복제하고 복제된 state값에 red값을 준다.
                }

                return newState; 
            }
            //복붙한 주소에 의해 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="
            
                store.dispatch({type:'CHANGE_COLOR', COLOR:'red'}); //store에 dispatch 함수를 호출해 type 객체를 주는데 이것을 반드시 있어야 한다.
            ">
        </div>
    `;
}
red();
        </script>
    </body>
</html>

console에 store.getState()를 입력하여 결과를 확인해보면 red 값으로 변경된 것을 확인할 수 있다.


reducer라는 함수가 하는 역할은 action의 값과 이전의 state값을 이용해 새로운 state 값을 리턴해 새로운 state값으로 store의 값을 변경해주는 것이다.

이때, 그 return 하는 값은 원본을 바꾸는 것이 아니라 이전에 있었던 값을 복제한 결과를 return 해야 한다.

 

강의 영상 - https://youtu.be/6n4MCp4pI5A