Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Redux 기초
/*
# Redux 기초
## 데이터 흐름
1. 액션을 스토어에 보냄.
2. Redux 스토어가 지정된 리듀서 함수들을 호출함. 이 때 현재 상태와 액션이 같이 넘어간다.
3. 루트 리듀서가 각 리듀서의 출력을 합쳐서 하나의 상태 트리로 만듬.
4. 반환된 상태 트리를 스토어에 저장함.
## 파일
action
todos.jsx // actions
reducers/
todos.jsx // reducer
todoApp.jsx // root reducer
store/
todoApp.jsx // store = createStore(rootReducer)
index.jsx
*/
/* action/todos.jsx */
export const ADD_TODO = 'ADD_TODO';
export const COMPLETE_TODO = 'COMPLETE_TODO';
export const SET_VISIBILITY_FILTER = 'SET_VISIBILITY_FILTER';
export const VisibilityFilters = {
SHOW_ALL: 'SHOW_ALL',
SHOW_COMPLETED: 'SHOW_COMPLETED',
SHOW_ACTIVE: 'SHOW_ACTIVE'
};
export function addTodo(text) {
return {
type: ADD_TODO,
text: text
};
}
export function completeTodo(index) {
return {
type: COMPLETE_TODO,
index: index
};
}
export function setVisibilityFilter(filter) {
return {
type: SET_VISIBILITY_FILTER,
filter: filter
};
}
/* reducers/todoApp.jsx */
import { combineReducers } from 'redux'
import { todos, visibilityFilter } from '../reducers/todos'
const todoApp = combineReducers({
todos,
visibilityFilter
});
export default todoApp
/* reducers/todos.jsx */
import { ADD_TODO, COMPLETE_TODO, SET_VISIBILITY_FILTER, VisibilityFilters } from '../action/todos'
export function todos(state = [], action) {
switch (action.type) {
case ADD_TODO:
return [...state, {
text: action.text,
completed: false
}]
case COMPLETE_TODO:
return [
...state.slice(0, action.index),
Object.assign({}, state[action.index], {
completed: true
}),
...state.slice(action.index + 1)
]
default:
return state
}
}
export function visibilityFilter(state = VisibilityFilters.SHOW_ALL, action) {
switch (action.type) {
case SET_VISIBILITY_FILTER:
return action.filter
default:
return state
}
}
/* store/todoApp.jsx */
import { createStore } from 'redux'
import todoApp from '../reducers/todoApp'
export let store = createStore(todoApp)
/* index.jsx */
import { store } from './store/todoApp'
import { addTodo, completeTodo, setVisibilityFilter } from './action/todos'
import { VisibilityFilters } from './action/todos'
let unsubscribe = store.subscribe( () => {
console.log(store.getState())
})
store.dispatch(addTodo("Learn about actions"))
store.dispatch(addTodo("Learn about reducres"))
store.dispatch(addTodo("Learn about store"))
store.dispatch(completeTodo(0))
store.dispatch(completeTodo(1))
store.dispatch(completeTodo(2))
store.dispatch(setVisibilityFilter(VisibilityFilters.SHOW_COMPLETED));
unsubscribe()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.