๐ 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)
๋ฐ์ํ
'Front-end > Redux' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
Redux Action๊ณผ Reducer์ Store์ ๊ด๊ณ์ฑ (0) | 2021.09.28 |
---|---|
React๋ฅผ ์ฐ๋ค๋ณด๋ Redux๊ฐ ๊ถ๊ธํด์ก๋ค (0) | 2021.08.18 |
๋๊ธ