Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
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
관리 메뉴

히바리 쿄야 와 함께 하는 Developer Cafe

[4일차] React 프로그래밍 정석/p472 ~ p584 / 미들웨어, Redux-pack 으로 비동기 제어하기 본문

React

[4일차] React 프로그래밍 정석/p472 ~ p584 / 미들웨어, Redux-pack 으로 비동기 제어하기

TWICE&GFRIEND 2021. 4. 27. 00:19

미들웨어 구조 요소

 

 

 

미들웨어

 

미들웨어는 아래와 같은 형태의 함수입니다. 아래와 같은 형태인 이유는, action => next(action) 영역에서 store 와 next 를 사용하기 위함입니다. 미들웨어를 작성할 때, 스토어가 필요한 경우가 많이 있습니다. 그리고 next 함수는 리덕스에서 넘겨주는 함수이며, 다음에 호출될 어떤 함수를 의미합니다.

 

 

const myMiddleware = store => next => action => next(action);

 

 

 

좀 더 이해하기 쉽게 미들웨어의 예를 들어보겟습니다. 두개의 미들웨어가 있고, 스토어를 생성할때 두개의 미들웨어를 등록해주고 있습니다. 그 다음 간단한 액션을 하나 실행하고 있습니다.

 

 

 

// 미들웨어
const middleware1 = store => next => action => {
  console.log('middleware1 start');
  const result = next(action);
  console.log('middleware1 end');
  return result;
}
const middleware2 = store => next => action => {
  console.log('middleware2 start');
  const result = next(action);
  console.log('middleware2 end');
  return result;
}

// 리듀서
const myReducer = (state, action) => {
  console.log('myReducer');
  return state;
}

// 스토어
const store = createStore(myReducer, applyMiddleware(middleware1, middleware2));

// 액션 실행
store.dispatch({ type: 'someAction' })

 

 

앱을 실행해 보면 아래와 같은 절차대로 실행됩니다. 미들웨어의 next 함수는 다음 미들웨어의 함수를 호출합니다. 하지만 마지막 미들웨어인 경우에 next 함수는 리듀서를 호출합니다. 따라서 아래와 같이 실행됩니다.

 

 

1. 처음에 상태값을 초기화 하기 위해서 리듀서가 먼저 실행 (미들웨어 없이 리듀서만 실행)

2. 프로그램이 액션을 실행 (dispatch 호출)

3. 미들웨어 1번 실행

4. 미들웨어 1번의 next 호출

5. 미들웨어 2번이 실행

6. 미들웨어 2번의 next 호출

7. 리듀서 실행

8. 미들웨어 2번 종료

9. 미들웨어 1번 종료

 

 

상태값을 출력하는 미들웨어

이 미들웨어는 상태값을 가져오기 위해 스토어를 사용하고 있습니다. 우선 next를 호출하면 리듀서 함수를 호출하기 때문에 상태값이 변경이 될 것입니다. 이렇게 상태값이 변경이 되기 전에 미들웨어에서는 상태값을 출력을 합니다. 그 다음 next 함수로 리듀서 함수를를 호출 한 후에 다시한번 변경된 상태값을 출력합니다.

 

 

// 미들웨어
const printLog = store => next => action => {
  console.log(`prev state = ${JSON.stringify(store.getState())}`);
  const result = next(action);
  console.log(`next state = ${JSON.stringify(store.getState())}`);
  return result;
}

// 리듀서
const myReducer = (state = { name: 'horong' }, action) => {
  console.log('myReducer');
  switch(action.type) {
    case 'someAction':
      return {...state, name:'horong123'}
    default:
      return state;
  }
  return state;
}

// 스토어
const store = createStore(myReducer, applyMiddleware(printLog));

// 액션 실행
store.dispatch({ type: 'someAction' })
Comments