Redux 공부, 생활코딩

Tony·2021년 7월 12일
0

javascript

목록 보기
2/61

1. Redux란?

  • A Predictable State Container for JS Apps
    • 예측가능한 상태컨테이너, JS 앱을 위한

2. Redux 동작 흐름

어떻게 동작하는 가?

store : 은행, 정보가 저장되는 곳

  • state : store안의 실제 정보가 저장되는 곳
    • state에 직접 접속하는 것은 금지되어 있음

reducer : store를 만들면서 공급해줘야 하는 함수

function reducer(oldState, action) {
  // ...
}
var store = Redux.createStore(reducer);

render : redux랑 상관없이 UI를 만드는 역할을 하는 내 코드

function render() {
  var state = store.getState(); // state값을 가져와서
  // ...
  document.querySelector('#app').innerHTML = ` // state값을 이용해서 UI를 만듦
	<h1>WEB</h1>
	// ...
  `
}

dispatch, subscribe, getState : 은행 창구 직원

  • render와 협력해서 app을 만듦
  • state값이 바뀔 때 마다 render()가 실행되려면? subscribe
store.subscribe(render);

게시글이나 댓글을 작성하면 바로 UI가 바뀔 때 (submit버튼을 통해)

<form onsubmit="
  // ...
  store.dispatch({type:'create', payload(title:title, desc:desc}});
">

action

{type:'create', payload(title:title, desc:desc} // 이 객체가 action
  • action이 dispatch에 전달이 됨

dispatch : 창구 직원

  • 역할
    • reducer를 호출해서 state값을 바꿈
    • 위 작업이 끝나면 subscribe를 이용해서 render()를 호출(화면 갱신)
  • reducer 호출 시 두 개의 값을 전달
    • 현재의 state값
    • action을 전달({type:'create', payload(title:title, desc:desc})

reducer : 은행 장부에 어떤 것을 했는지 적는 사람

  • state를 입력값으로 받고, action을 참조해서 새로운 state값을 만들어서 return해주는, state를 가공해주는, 가공자
function reducer(state, action) {
  if(action.type === 'create') { // action에 대응하는 reducer 코드
    var newContents = oldState.content.concat();
    var newMaxId - oldState.maxId + 1;
    newContents.push({id:newMaxId, title:action.payload})
    return Object.assign({}, state, {
      contents: newContents,
      maxId:newMaxId,
      mode:'read',
      selectedId:newMaxId
    });
  }
}

state값 변경 -> dispatch가 subscribe에 등록된 state와 연결된 render를 호출

  • render가 호출 되면 getState로 state값을 가져와서 화면 갱신

state : 은행 장부

  • 변경 : dispatch, reducer를 통해
  • 읽기 : getState를 통해

3. Redux의 장점

application 구현의 복잡성을 낮출 수 있다.

Redux Dev Tools - 크롬 웹 스토어

  • app의 state에 대한 버전관리 : 과거 상태로 돌아갈 수 있음

4. 간단하게 리덕스 사용해보기

function reducer(state, action) { // 현재 state값 - 직접 변경하지말고, 복사 후 복사본을 변경 후 return하자 : Object.assign({}, {name:'tony'}, {city:'seoul'}); // {name:'tony', city:'seoul'}
  if(state === undefined) {
    return {color:'yellow'}
  }
  var newState;
  if(action.type === 'CHANGE_COLOR'){
    newState = Object.assign({}, state, {color: action.color});
  }
  return newState;
}
var store = Redux.createStore(reducer);
function red() {
  var state = store.getState();
  document.querySelector('#red').innerHTML = `
	<div class="container id="component_red" style="background-color:${state.color}">
	  <input type="button" value="fire">
	</div>
`
}
store.subscribe(red); // state값이 바뀔 때 마다 red함수가 호출
red();

5. Redux의 선물 : 시간여행

  • redux dev tool

참고 문헌

profile
움직이는 만큼 행복해진다

0개의 댓글