npm install —save redux
→ CDN으로 사용 가능
<script src="<https://cdnjs.cloudflare.com/ajax/libs/redux/4.0.1/redux.js>"></script>
// 디스패치에서 액션이 들어오면 액션 값 + state 값을 참조해 새로운 state 생성
function reducer(state, action) { // 파라미터 고정
// 초기값 설정
if ( state == undefined ) {
return { color: 'yellow' };
}
}
// store 생성
var store = Redux.createStore(reducer);
console.log(store.getState());
type 프로퍼티는 반드시 있어야 함 !!
시간 여행을 위해 state의 복사본을 수정, 저장하기 → Object.assign({}, 복제 객체, 추가/수정 내용);
<input type="button" value="fire" onClick="
store.dispatch({type: 'CHANGE_COLOR', color: 'red'});
"/>
function reducer(state, action) { // 파라미터 고정
console.log(state, action);
// 초기값 설정
if ( state == undefined ) {
newState = { color: 'yellow' };
}
// state 변경
var newState;
if ( action.type === 'CHANGE_COLOR') {
newState = Object.assign({}, state, { color : acton.color });
}
return newState;
}
function red() {
document.querySelector("#red").innerHTML = `
<div class="container" id="component_red" style="background-color:${state.color}">
<h1>red</h1>
<input type="button" value="fire" onClick="
store.dispatch({type: 'CHANGE_COLOR', color: 'red'});
"/>
</div>
`;
}
red();
store.subscribe(red);
// blue, green도 마찬가지로 ...
→ 각 부품 ( red, blue, green ) 간의 의존성을 낮춰줄 수 있음