
react redux가 아닌 기본 redux에 대한 내용입니다. (출처 - 생활코딩)

A predictable state container for Javascript apps.
(자바스크립트 앱을 위한 예측 가능한 상태 저장소)
Single Source of Truth
하나의 store, 하나의 state 객체를 갖는다. 중앙 집중적으로 상태가 관리된다.
State is read-only
state를 직접 변경하는 것은 불가능하며, state의 변경을 위해서는 action이라는 객체를 이용해야 한다.
Changes are made with pure functions
reducer를 통해 상태 변화에 대해 예측이 가능하다.
store는 외부로부터 철저하게 차단되어야 한다.dispatch, reducer, getState)를 통해서만 관리될 수 있다.state가 변경될 때마다 state의 데이터를 사용하는 모든 곳에 각각에게 해당하는 명령을 내릴 수 있다.
store를 생성하면 자동으로 그 안에 state도 생성된다.createStore의 인자로 넘어가는 함수로, reducer를 구현하는 것이 redux를 만드는 일의 상당 부분을 차지한다. 새로운 state 값을 가공하여 리턴한다.function reducer(oldState, action) (
// ...
}
var store = Redux.createStore(reducer);
getState를 통해 받은 state 값을 이용하여 UI를 만들고 화면을 그린다.function render() {
var state = store.getState();
// ...
document.querySelector('#app').innerHTML = `
<h1>REDUX</h1>
...
`
}
subscriber에 render를 등록하면 state가 변경될 때마다 render가 호출되며 UI가 갱신된다.store.subscribe(render);
type과 action을 전달받아,state와 action을 넘겨주며 reducer를 호출하여 state의 값을 바꾼다.subscribe를 이용하여 render를 호출한다.store.dispatch({type:'create', action});
let store = Redux.createStore(reducer);
function reducer (state, action) { }
function reducer (state, action) {
if (state === undefined) {
return { color: 'yellow'}
}
let state = store.getState();
console.log(state); // { color: 'yellow' } 출력
store.dispatch({type: 'CHANGE_COLOR', color: 'red'});
reducer 함수는 변경된 state 값을 리턴한다. 주의할 점은 state를 그대로 수정하여 리턴하지 않고 state를 복제하여 복제된 state를 수정하여 리턴해야 한다. (그래야 예측 가능하게 동작시킬 수 있다.)
function reducer(state, action) {
// 초기값 세팅
if (state === undefined) {
return { color: 'yellow' };
}
// 전달받은 action type에 따른 state 변경 (state 복제본을 통해)
let newState;
if (action.type === 'CHANGE_COLOR') {
newState = Object.assign({}, state, {color: action.color});
}
// 변경된 state 값 리턴
return newState;
}
하지만 예시에서 state의 color를 red로 변경해주어도, 당장 UI 색이 red로 변하지는 않는다. reducer는 store의 state 값을 변경시킬 뿐이다. 이 변화를 UI에 반영시키지는 않는다. 이는 render가 담당한다.
store.subscribe(render);
chrome 확장 프로그램 "redux dev tool"의 설치가 필요하다.