본문 바로가기

[IT] 🐦기초 쌓기

[Redux] 순수 Redux (JS)에 대한 설명

리덕스의 흐름

Store : 정보 저장 

실제 저장하는 곳 : store안에 State 

 

GetState 란? 

State를 가져오기 위해 사용 

>> state객체로 접근하여 State의 데이터를 가져온다

(GetState함수를 호출하여 사용)

 

Subscribe 

- 렌더(Render)라는 함수 (내가 미리 구독한 함수 불러오기 -- 리렌더링과 유사)

리액트가 없는 순수 리덕스는 자동으로 ui가 변하지 않으므로 자동으로 ui를 바뀌게 하기 위해 렌더라는 함수 등록

 

Dispatch 

- State값을 바꾸고 싶을 때 호출

- 실제로 하고 싶은 것을 action에 담아서 전달 

- dispatch가 reducer라는 함수를 호출(실행) , 두 개의 값을 보낸다 (현재State값, action)

 

리듀서 Reducer

>> State를 변경, 반환

 

 

실습

 

 

1. store를 만들 때 reducer 함수를 등록

2. red에 있는 '실행'버튼 클릭

3. store.dispatch함수를 실행 (클라이언트)

-------------------------------------

(store 동작부)

- dispatch가 현재 state와 전달받은 action으로 reducer 함수를 호출

- reducer함수는 전달받은 action을 이용해 state를 변경

- reducer함수는 변경된 state를 return한다.  (디스패치가 이걸 전달 받는다 )

- dispatch는 reducer에게 state를 전달 받으면 (state변경이 끝났으므로 이를 알려줘야겠다) subscribe에 등록된 함수를 실행한다. (어떤걸 실행할지 몰라서 subscribe에 등록되어 있는것만 실행)

 

 


1. redux 사용할 준비 

- reducer 함수 만들기

- reducer 함수 이용해 store 만들기 

- 만들어진 store안에 subscribe 함수를 이용해 state가 변경되었을 때 실행할 함수를 등록하기 

      function reducer(state = { color: 'orange' }, action) {
        // = { color: 'orange' } 이렇게 기본값을 세팅한다.
        //state값과 action을 인자로
        // console.log(action);
        if (action.type == 'CHANGE') return { color: action.color }; // 타입이 change라면 컬러 값을 보내줘라
        return state; //변경된 state 리턴
      }
      var store = Redux.createStore(reducer); // store를 만들고, 리듀서 등록하기
      
// 내가 만든 함수 실행
      //  예시) alert(store.getState().color);
      //렌더하는 함수를 가져오는 함수 subscribe -- react와 달리 리렌더링이 일어나지 않으므로 이 과정이 필요
      store.subscribe(red);

 

 <!-- redux 연결 CDN -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.2.0/redux.min.js"></script>
 function reducer(state = { color: 'orange' }, action) {
        // = { color: 'orange' } 이렇게 기본값을 세팅한다.
        //state값과 action을 인자로
        console.log(action);
        return state; //변경된 state 리턴
      }

 

2. red에 있는 '실행'버튼을 클릭

store.dispatch({type:CHANGE, color:'red'}); 

    <div id="red">
      <div class="container" id="component_red">
        <h1>red</h1>
        <input
          type="button"
          value="실행"
          onclick="store.dispatch({type:'CHANGE', color:'red'});"
        />
        <!-- <input type="button" value="실행" onclick="red()" 이 안에 이제 액션을 담는다. /> -->
      </div>
    </div>

 

3. store.dispatch함수를 실행 (클라이언트)

-------------------------------------

(store 동작부)

- dispatch가 현재 state와 전달받은 action으로 reducer 함수를 호출

- reducer함수는 전달받은 action을 이용해 state를 변경

- reducer함수는 변경된 state를 return한다.  (디스패치가 이걸 전달 받는다)

- dispatch는 reducer에게 state를 전달 받으면 (state변경이 끝났으므로 이를 알려줘야겠다) subscribe에 등록된 함수를 실행한다. (어떤걸 실행할지 몰라서 subscribe에 등록되어 있는것만 실행)

function red() {
        var state = store.getState();
        document.querySelector('#component_red').style.backgroundColor =
          state.color;
        // document.querySelector('#component_red').style.backgroundColor = 'red';
        // document.querySelector('#component_green').style.backgroundColor =
        //   'red';
        // document.querySelector('#component_yellow').style.backgroundColor =
        //   'red';
      }

 

전체코드

<html>
  <head>
    <!-- redux 연결 CDN -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.2.0/redux.min.js"></script>
    <style>
      .container {
        border: 3px solid black;
        padding: 10px;
        width: 100px;
        height: 100px;
      }
    </style>
  </head>
  <body>
    <div id="red">
      <div class="container" id="component_red">
        <h1>red</h1>
        <input
          type="button"
          value="실행"
          onclick="store.dispatch({type:'CHANGE', color:'red'});"
        />
        <!-- <input type="button" value="실행" onclick="red()" 이 안에 이제 액션을 담는다. /> -->
      </div>
    </div>
    <div id="green">
      <div class="container" id="component_green">
        <h1>green</h1>
        <input type="button" value="실행" onclick="green();" />
      </div>
    </div>
    <div id="yellow">
      <div class="container" id="component_yellow">
        <h1>yellow</h1>
        <input type="button" value="실행" onclick="yellow();" />
      </div>
    </div>
    <script>
      function reducer(state = { color: 'orange' }, action) {
        // = { color: 'orange' } 이렇게 기본값을 세팅한다.
        //state값과 action을 인자로
        // console.log(action);
        if (action.type == 'CHANGE') return { color: action.color }; // 타입이 change라면 컬러 값을 보내줘라
        return state; //변경된 state 리턴
      }
      var store = Redux.createStore(reducer); // store를 만들고, 리듀서 등록하기

      function red() {
        var state = store.getState();
        document.querySelector('#component_red').style.backgroundColor =
          state.color;
        // document.querySelector('#component_red').style.backgroundColor = 'red';
        // document.querySelector('#component_green').style.backgroundColor =
        //   'red';
        // document.querySelector('#component_yellow').style.backgroundColor =
        //   'red';
      }
      function green() {
        document.querySelector('#component_red').style.backgroundColor =
          'green';
        document.querySelector('#component_green').style.backgroundColor =
          'green';
        document.querySelector('#component_yellow').style.backgroundColor =
          'green';
      }
      function yellow() {
        document.querySelector('#component_red').style.backgroundColor =
          'yellow';
        document.querySelector('#component_green').style.backgroundColor =
          'yellow';
        document.querySelector('#component_yellow').style.backgroundColor =
          'yellow';
      }
      // 내가 만든 함수 실행
      //   alert(store.getState().color);
      //렌더하는 함수를 가져오는 함수 subscribe -- react와 달리 리렌더링이 일어나지 않으므로 이 과정이 필요
      store.subscribe(red);
    </script>
  </body>
</html>