티스토리 뷰

Intro

  1. 데이터를 연동하려면 일반적으로 서버에 구현된 REST API에 ajax를 요청하여 데이터를 가져오거나 입력
  2. 서버의 API를 호출할 때는 세 가지 상태를 관리
    1) 요청 시 : [로딩]
    2) 응답 시 : [성공] or [실패]
    위 세 상태에 대한 처리를 해야 한다.
  3. 위 작업을 react component의 state만 사용해도 관리할 순 있다. but
  4. 리덕스, 리덕스 미들웨어를 사용하면 간편하게 관리할 수 있다고 합니다.

15.1 미들웨어 이해

  1. 미들웨어 : action의 dispatch 발생 시, reducer에서 이를 처리하기 전에 사전에 지정된 작업을 실행하는 영역?
  2. 미들웨어 : action과 reducer 사이의 중간자

갑자기 궁금한 것
버튼이 하나 있다. 그 옆에 숫자가 하나 있다. 버튼을 누르면 숫자에 1이 더해진다.
여기서 action이란 무엇인가?
버튼을 누르는 행위 자체가 action인가? 그렇다면 그 action을 수용?하는 것은 하나의 thread인가?
숫자를 1 증가시키는 것은 어느 부분이 담당하는가? reducer가 하는가? reducer는 하나의 thread인가?
위에 적어 놓은 것들이 다 맞다면, middle ware는 thread와 thread 사이에 통신으로 연결된 또 다른 thread인가?

15.2 비동기 작업을 처리하는 미들웨어

  1. redux-thunk, redux-promise-middleware, redux-pender
  2. 위 세 라이브러리는 각자 다른 방식으로 비동기 액션을 처리한다.

15.2.1 redux-thunk

  1. 특정 작업을 나중에 할 수 있도록 미루려고 함수 형태로 감싼 것
  2. 이 미들웨어는 객체가 아닌 함수도 dispatch할 수 있게 합니다.
  3. 1초 뒤에 액션이 디스패치되는 example code down below ^^
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 function incrementIfOdd(){
    return (dispatch, getState) => {
        const {counter} = getState();
        if (counter%2 ===0){return;}
        dispatch(increment());
    }
}


export default handleActions({
    [INCREMENT]: (state, action) => state + 1,
    [DECREMENT]: (state, action) => state - 1
}, 0);
  1. 객체가 아니라 이렇게 함수를 반환하는 함수는 액션 생성 함수라 하지 않고 thunk 생성 함수라고 한다.
  2. thunk 생성 함수에서는 dispatch와 getState를 파라미터로 가지는 새로운 함수를 만들어서 반환해야 한다.

15.2.2 웹 요청 처리

  1. redux-thunk를 사용한 비동기 작업을 처리해 보자
  2. axios라는 Promise-기반-HTTP 클라이언트 라이브러리를 사용해서 웹 요청 테스트 해봅시다.
  3. Promise는 ES6 문법에서 비동기 처리를 다루는 데 사용하는 객체
function printLater(number, fn){
  setTimeout(
    function(){
      console.log(number);
      if(fn) fn();
    }, 1000
    );
}

printLater(1, function(){
  printLater(2, function(){
      printLater(3);
  })
})

// 이렇게 하면 1\n 2\n 3\n이 출력 됩니다. 1초 간격으로 
// 모양이 지저분하죠, 콜백 지옥과 같은 모양 
// 기존 JS의 이와 같은 문제를 해결해 주는 것이 Promise!
function printLater(number){
  return new Promise( // 새 promise를 만들어서 return
    resolve => {
      setTimeout(
        () => {console.log(number); 
               resolve(); // promise가 끝났음을 알립니다.
        }, 1000
      )
    }
  )
}

printLater(1)
  .then(()=>printLater(2))
  .then(()=>printLater(3))
  1. Promise는 값을 리턴하거나 오류를 발생시킬 수도 있다.
  2. Promise에서 결과를 반환할 때 resolve(결과 값)를 사용, 오류를 발생시킬 떄는 reject(오류)를 사용
  3. 반환하는 결과 값 or 오류는 각각 .then(), .catch()에 전달하는 함수의 파라미터로 설정된다.
function printLater(number){
  return new Promise(
    (resolve, reject) => {
      if (number>4){
        return reject('number is greater than 4');
      }
      setTimeout(
        () => {console.log(number); resolve(number+1);},
        1000
      )
    }
  )
}

printLater(1)
    .then(e=>printLater(e))
    .then(e=>printLater(e))
    .then(e=>printLater(e))
    .then(e=>printLater(e))
    .catch(e=>console.log(e));
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG more
«   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
글 보관함