2022이전/React
REACT_REDUX\_미들웨어(redux-logger, redux-thunk)
바로퇴장
2020. 1. 27. 15:36
##redux-logger
yarn add redux-logger
src/store.js
import { createStore } from 'redux';
import modules from './modules';
import { applyMiddleware } from 'redux'; //미들웨어 적용하는 함수 이다.
import { createLogger } from 'redux-logger';
const logger = createLogger();
const store = createStore(modules, applyMiddleware(logger));
export default store;
createLogger를 통하여 미들웨어의 상태를 알수 있다
counter페이지 예시
action INCREMENT @ 15:10:59.618
redux-logger.js:1 prev state {counter: 0}
redux-logger.js:1 action {type: "INCREMENT", payload: Proxy}
redux-logger.js:1 next state {counter: 1}
redux-thunk
yarn add redux-thunk
thunk는 특정 작업을 나중에 할 수 있도록 미루려고 함수 형태로 감싼 것을 의미합니다.
Redux-thunksms 객체가 아닌 함수도 디스패치할 수 있게 합니다. 일반 액션 객체로는 특정 액션을 디스패치한 후 몇 초 뒤에 실제로 반영시키거나 현재 상테에 따라 아예 무시하게 만들 수 없습니다.
이 미들에어는 함수를 디스패치할 수 있게 함으로써 일반 액션 객체로는 할 수 없는 작업들도 할 수 있게 합니다.
src/store.js
import { createStore } from 'redux';
import modules from './modules';
import { applyMiddleware } from 'redux'; //미들웨어 적용하는 함수 이다.
import { createLogger } from 'redux-logger';
import ReduxThunk from 'redux-thunk';
const logger = createLogger();
const store = createStore(modules, applyMiddleware(logger, ReduxThunk));
export default store;
src/module/counter.js
import { handleActions, createAction } from 'redux-actions';
const INCREMENT = 'INCREMENT';
const DECREMENT = 'DECREMENT';
export const increment = createAction(INCREMENT);
export const decrement = createAction(DECREMENT);
export const incrementAsync = () => dispatch => {
setTimeout(
() => { dispatch(increment())},
1000
);
}
export const decrementAsync = () => dispatch => {
setTimeout(
() => { dispatch(decrement())},
1000
)
}
export default handleActions({
[INCREMENT]: (state, action) => state + 1,
[DECREMENT]: (state, action) => state - 1
}, 0);
위처럼 setTimeout함수를 이용해서 딜레이를 주고 싶을 때 dispatch가 요청한후 다음 function을 진행하게 된다. 이러한 비동기적 처리를 할 때 redux-thunk를 사용한다.