액션을 주면, 그 액션이 적용되어 달라진 결과를 만들어 준다. 물론 달라지지 않을수도?
그냥 함수이다. 단지 Pure Function 일 뿐이다.
같은 input 을 받으면 같은 output 을 뱉어내야 한다. 시간의 흐름에 따라 값이 변한다거나 하는
로직이 들어가면 안된다.
Immutable
Reducer 를 통해서 state 가 달라졌음을 Redux 가 인지하는 방식이기 때문에
오리지널 state 와 새로 바뀐 state 가 별도의 객체로 만들어져야 한다.
function Reducer(previous state, action) {
...
return newState;
}
액션을 받아서 state 를 리턴해 준다.
// todo.js
import { ADD_TODO, COMPLETE_TODO } from "../actions";
const initialState = [];
export default function todos(previousState = initialState, action) {
if (action.type === ADD_TODO) {
return [...previousState, { text: action.text, done: false }];
}
if (action.type === COMPLETE_TODO) {
return previousState.map((todo, index) => {
if (index === action.index) {
return { ...todo, done: true };
}
return todo;
});
}
return previousState;
}
// filter.js
import { SHOW_ALL, SHOW_COMPLETE } from "../actions";
const initialState = "ALL";
export default function filter(previousState = initialState, action) {
if (action.type === SHOW_COMPLETE) {
return "COMPLETE";
}
if (action.type === SHOW_ALL) {
return "ALL";
}
return previousState;
}