yarn add redux react-redux
// modules/counter.js
const INCREASE = 'counter/INCREASE';
const DECREASE = 'counter/DECREASE';
// modules/todos.js
const CHANGE_INPUT = 'todo/CHANGE_INPUT'; // input 값 변경
const INSERT = 'todo/INSERT'; // 새로운 todo를 등록함
const TOGGLE = 'todo/TOGGLE'; // todo를 체크 / 체크해제
const REMOVE = 'todo/REMOVE'; // todo 제거
// modules/counter.js
...
export const increase = () => ({type : INCREASE})
export const decrease = () => ({type : DECREASE})
// modules/todos.js
...
export const changeInput = input => ({
type : CHANGE_INPUT,
input
});
let id = 3;
export const insert = text => ({
type : INSERT,
todo : {
id : id++,
text,
done : false,
}
});
export const toggle = id => ({
type : TOGGLE,
id
});
export const remove = id => ({
type : REMOVE,
id
})
// modules/counter.js
...
const initialState = {
number : 0,
}
function counter(state = initialState, action){
switch (action.type) {
case INCREASE :
return {
number : state.number + 1
};
case DECREASE :
return {
number : state.number -1
}
default :
return state;
}
}
export default counter;
// modules/todos.js
...
const initialState = {
input : '',
todos : [
{
id : 1,
text : 'test content01',
done : true,
},
{
id : 2,
text : 'test content02',
done : false,
}
]
}
function todos(state = initialState, action) {
switch (action.type) {
case CHANGE_INPUT :
return {
...state,
input : action.input,
}
case INSERT :
return {
...state,
todos : state.todos.concat(action.todo)
}
case TOGGLE :
return {
...state,
todos : todos.map(todo => (
todo.id === action.id ? {...todo, done : !todo.done} : todo
))
}
case REMOVE :
return {
...state,
todos : state.todos.filter(todo => todo.id !== action.id)
}
default :
return state
}
}
export default todos;
// modules/index.js
import {combineReducers} from 'redux';
import counter from './counter';
import todos from './todos';
const rootReducer = combineReducers({
counter,
todos,
})
export default rootReducer;