Notice
Recent Posts
Recent Comments
Link
«   2024/03   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
Tags
more
Archives
Today
Total
관리 메뉴

개발블로그

Redux (2018.06.30) 본문

Redux (2018.06.30)

학교옆메추리 2020. 5. 28. 13:34

Action

— object : { type: SOME_TYPE [, USER_DEFINE_DATA ]}
우리는 액션객체를 리듀서에 전달함으로써 상황에 따라 원하는대로 스토어의 상태를 변경시킬 수 있다.
액션의 type은 꼭 지정해주어야 하며, 타입값은 이 액션이 할 일로 하자!
ex) 값을 증가시키는 액션 → type : INCREMENT

Tip) type을 자주 사용하게 된다면 상수변수로 등록해놓자!
const INCREMENT = “increment”; 이런식으로…

Reducer

— params : state, action
파라미터로 받은 액션객체의 타입(action.type)에 따라 상태(state)를 어떻게 업데이트 할 것인지를 정의하는 함수.
state는 immutable하게 유지시켜주어야 한다.

// 배열 원소를 추가하고싶다!
return list.push(0); // (X)

return [...list, 0]; // (O)

return list.concat(0); // (O)// 배열 원소를 삭제하고싶다!

// 수정은 두 slice 사이에 원하는 값을 추가하면 된다.// 객체에 원소를 추가하고싶다!
return [ ...list.slice(0, index), ...list.slice(index + 1) ];

// {}에 myObject를 복사하고 myData: data를 추가한다.
return Object.assign({}, myObject, myData: data);

// OR
return {...myObject, myData: data};

 

Store

const store = redux.createStore(Reducer) // 스토어 생성함수.
스토어에 담긴 정보를 사용하고 싶은 컴포넌트는 생성된 스토어를
구독(subscribe)하면 된다.

 store.subscribe(listener) // 스토어 구독함수.
생성된 스토어를 구독하면, 스토어에 저장된 상태가 변경될 때마다 파라미터로 보낸 listner 함수가 호출된다.
우리는 listner 함수를 통해 스토어의 변화에 따른 작업을 수행할 수 있다.

 store.dispatch(action) // 스토어 상태변경함수.
액션객체를 받아 현재 상태값과 함께 리듀서에게 전달한다.
우리가 리듀서에 정의해놓은대로 스토어의 상태값이 변경되어 listener 함수가 호출되고, 이에 따라 해당 컴포넌트들이 리랜더링된다.

— store.getState() // 스토어의 상태를 가져오는 함수.
스토어의 상태를 이 함수를 통해 알 수 있다.

createStore의 내부 동작

const createStore = reducer => {
	let state;
	let listeners = [];const getState = () => state;
    const dispatch = action => {
		state = reducer(state, action);
		listeners.forEach(listener => listener());
	};
    const subscribe = listener => {
		listeners.push(listener);
		return () => {
			listeners = listeners.filter(l => l !== listener);
		};
	};// Store를 initial state로 초기화해준다.
    
	dispatch({});return { getState, dispatch, subscribe };
}

combineReducers의 내부 동작

const combineReducers = reducers => {
	return (state = {}, action) => {
    	return Object.keys(reducers).reduce(
			(nextState, key) => {
            	nextState[key] = reducers[key](state[key], action);
				return nextState;
        },);
	};
};

Dan abramov의 Redux 입문 강의를 공부하면서 정리해 보았다.

 

 

 

 

'' 카테고리의 다른 글

JS Class (2018.10.04)  (0) 2020.05.28
JS prototype (2018.10.01)  (0) 2020.05.28
Immutable.js (2018.06.26)  (0) 2020.05.28
CORS (2018.06.24)  (0) 2020.05.28
Webpack (2018.06.23)  (0) 2020.05.28