이고잉 님이 제작한 리덕스 강의 내용을 정리한 포스트입니다
생활코딩 - Redux
자바스크립트를 위한, 예측 가능한 상태 저장소
state는 직접적으로 접속하는 것이 불가
function reducer(oldState, action) {
//...
}
var store = Redux.createStore(reducer);
function render() {
// getState를 통해서 state값을 가져와서
var store = store.getState();
//...
// 여기서 변경된 상태값을 UI에 출력
document.querySelector('#app').innerHTML = `
<h1>WEB<h1>
....
`
}
store.subscribe(render);
// state의 값이 바뀔 때마다 render함수를 호출해 UI를 갱신시킴
store.dispatch
를 이용해 객체를 전송type: 'create'
해당 객체를 action이라고 하며 반드시 가지고 있어야 하는 값임
<form onsubmit="
//...
store.dispatch({type: 'create', payload: {title: title, desc: desc}});
">
function reducer(state, action){
if(action.type === 'create'){
var NewContents = oldState.contents.concat();
var newMaxId = oldState.MaxId+1;
NewContents.push({id: newMaxId, title: action.payload.title});
return Object.assign({}, state, {
contents: newContents,
maxId: newMaxId,
mode: 'read',
selectedId: newMaxId
});
📌 데이터가
집중화(Centralized)
되어 있어서예측 가능하며(Predictable)
데이터 흐름이 단방향이라서디버깅하기 쉽다(Debuggable)
. 또 리덕스와 연관된 좋은 생태계가 구축되어 있어서 필요에 맞게유연하게(Flexible)
구현할 수 있다.
📄 참조: 리덕스(Redux)는 왜 쓰는 건데!?
dispatch: 값을 변경시키고
getState: 변경된 값을 가져오고
subscribe: 값이 변경됐을 때 구동될 함수를 등록
reducer: state의 값을 변경