๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Front-end/Redux

Redux 3๊ฐ€์ง€ ์›์น™ ์ •๋ฆฌ

by ciocio 2021. 11. 4.

๐Ÿ“  The truth comes from one source

 

App์˜ ๋ชจ๋“  ์ƒํƒœ๋Š” ํ•˜๋‚˜์˜ ์ €์žฅ์†Œ์— ๊ฐ์ฒด ํŠธ๋ฆฌ ๊ตฌ์กฐ๋กœ ์ €์žฅ๋œ๋‹ค.

 

console.log(store.getState());

/*
 * {
 *    visibilityFilter: 'SHOW_ALL',
 *	  todos: [{
 *	    text: 'Consider using Redux',
 *      completed: true,
 *    }, {
 *		text: 'Keep all state in a single tree',
 *      completed: false
 *    }]
 * }
*/

 

 

๐Ÿ“  State is read-only

 

์ƒํƒœ ๋ณ€๊ฒฝ์€, ์•ก์…˜ ๊ฐ์ฒด(์–ด๋–ค ์ƒํƒœ ๋ณ€ํ™”๊ฐ€ ์ผ์–ด๋‚˜์•ผํ•˜๋Š” ์ง€ ๊ธฐ์ˆ ๋œ ๊ฐ์ฒด)๋ฅผ ํ†ตํ•ด์„œ๋งŒ ์ผ์–ด๋‚œ๋‹ค.

 

store.dispatch(action: Object)

store.dispatch({
  type: 'COMPLETE_TODO',
  index: 1;
})

store.dispatch({
  type: 'SET_VISIBILITY_FILTER',
  filter: 'SHOW_COMPLETED'
})

 

 

๐Ÿ“  Changes should be written as pure functions

 

์•ก์…˜์„ ์ธ์ž๋กœ ๋ฐ›์•„ ์ƒํƒœ๋ฅผ ๋ณ€ํ™”์‹œํ‚ค๋Š” reducer๋Š” ์ˆœ์ˆ˜ ํ•จ์ˆ˜๋กœ ๋งŒ๋“ค์–ด์•ผ ํ•œ๋‹ค.

reducer ๋Š” side effect ๋ฅผ ๋ฐœ์ƒ์‹œํ‚ค์ง€ ์•Š๋Š”๋‹ค.

 

function visibilityFilter(state = 'SHOW_ALL', action){
  switch(action.type){
    case 'SET_VISIBILITY_FILTER':
      return action.filter;
    default:
      return state;
  }
}

function todos(state = [], action){
  switch(action.type){
    case 'ADD_TODO':
      // ๊ธฐ์กด์˜ ์ƒํƒœ์— completed๊ฐ€ false๋กœ ์„ค์ •๋œ ํ• ์ผ์ด ์ถ”๊ฐ€๋œ 
      // ์ƒˆ๋กœ์šด ์ƒํƒœ๋ฅผ ๋ฆฌํ„ดํ•˜๋Š” ๊ฑธ ํ™•์ธํ•  ์ˆ˜ ์žˆ๋‹ค.
      return [
        ...state,
        {
          text: action.text,
          completed: false;
        }
      ]
    case 'COMPLETED_TODO':
      // ๊ธฐ์กด์˜ ์ƒํƒœ์— ํ•ด๋‹น action์˜ ์ธ๋ฑ์Šค์— ํ•ด๋‹นํ•˜๋Š” ๊ฐ์ฒด๋งŒ completed๋ฅผ true๋กœ ๋ฐ”๊ฟ”์„œ
      // ์ƒˆ๋กœ์šด ์ƒํƒœ๋ฅผ ๋ฆฌํ„ดํ•˜๋Š” ๊ฑธ ํ™•์ธํ•  ์ˆ˜ ์žˆ๋‹ค.
      return [
        ...state.slice(0, action.index),
        Object.assign({}, state[action.index], {completed: true}),
        ...state.slice(action.index + 1)
      ]
    default:
      return state;
  }
}

import { combineReducers, createStore } from 'redux'
let reducer = combineReducers({ visibilityFilter, todos })
let store = createStore(reducer)
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€