[React] 17. Redux-Thunk

dev·2020년 10월 23일
0

React

목록 보기
17/21

오늘은 Redux-Thunk에 대해 알아 보겠습니다.

redux-thunk는 리덕스에서 비동기 작업을 처리 할 때 가장 많이 사용하는 미들웨어입니다. 이 미들웨어를 사용하면 액션 객체가 아닌 함수를 디스패치 할 수 있습니다

const thunk = store => next => action => {

};

dispatch()가 일어나면 액션 생성함수로 가는데 이때 받는 인자가 객체가 아닌 함수로 받을 수 있다는 겁니다.

예를 들어

export const increase = (ten) => ({ type: INCREASE, number : ten});

가 있으면

export const increase = (ten) => (dispatch, getState) => { //로직 구현;
};

이렇게 변하는거죠

export const increase = store => next => action => {}

로 store를 사용하여 dispatch, getState를 접근 할 수 있고, reducer로 가는 걸 next로 통제하거나 action으로 reducer를 진행하게 만드는 것이죠

export const increase = (ten) => (dispatch, getState) => {
if(ten != null){
//ten이라는 값을 변경해서 보내거나
ten = 500;
}
else{
//다른 액션생성함수를 dispatch() 시키거나
}
};

이렇게 reducer로 가기 전에 끼어들어서 값이나 원래 dispatch애를 바꿀 수 있습니다.

의 getState는 사용 하지 않을거면 빼도 상관 없습니다.

그럼 redux-thunk를 사용할려면 적용을 시켜줘야합니다.

1.index.js

import ReduxThunk from 'redux-thunk';
import { createStore, applyMiddleware } from 'redux';
const store = createStore(
rootReducer,
applyMiddleware(ReduxThunk)
);

를 추가해줘야합니다.
store를 만들 때 해당 store에 미들웨어인 ReduxThunk를 applyMiddleware를 사용하여 적용시켜주면 됩니다.

profile
studying

0개의 댓글