redux middleware 직접 만들어보기

Judo·2021년 1월 12일
0

참고문서

미들웨어 템플릿

const middleware = store => next => action => { 
	// 하고 싶은 작업..
}

미들웨어는 결국 함수를 연달아 두번 리턴하는 함수다.

parameter의 의미

  • store

    • 리덕스 스토어 인스턴스, dispatch, getState, subscribe 내장함수를 갖고 있다.
  • next

    • 액션을 다음 미들웨어에 전달하는 함수
    • next(action) 형태로 사용
    • 다음 미들웨어가 없다면 리듀서에게 액션 전달
    • next를 호출하지 않는다면 액션이 무시되고 리듀서에 전달 안 됨.
  • action

    • 현재 처리하고 있는 액션 객체

  • 위 그림처럼 리덕스 스토어엔 여러 개의 미들웨어 등록 가능

  • 액션이 디스패치되면 첫 번째 미들웨어 호출

    • 미들웨어1 => next(action) 호출 => 미들웨어2 로 액션이 넘어감
    • 미들웨어1 => store.dispatch 호출 => 액션 추가

미들웨어 작성

//myLogger.js
const myLogger = store => next => action => {
  console.log(action); // 액션 출력 
  const result = next(action); // 다음 미들웨어 or 리듀서에게 액션 전달 
	
  
  console.log('\t', store.getState());
  // 만약 액션이 리듀서까지 전달되고 난 후의 상태를 확인하려면 next(action) 이후에 콘솔에 찍어본다.
  
	
  return result; // dispatch(action)의 결과물을 반환 (default: undefined)
}
export default myLogger;
// index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import rootReducer from './modules';
import myLogger from './middlewares/myLogger';

const store = createStore(rootReducer, applyMiddleware(myLogger));
// 스토어에 미들웨어를 적용 할 때에는 applyMiddleware 함수를 사용한다. 
ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
);
  • 콘솔 화면
profile
즐거운 코딩

0개의 댓글