
함수를 연달아서 2번 리턴하는 함수
Middleware는redux가 지니는 핵심기능
리덕스 미들웨어를 사용하면
action이dispatch된 다음,
reducer에서 해당action을 받아서 업데이트 하기 전에 추가적인 작업을 할 수 있다.추가적인 작업 ex)
1. 비동기 작업 처리
2. 백엔드 API 연동
3. 특정 조건에 따라 액션이 무시되게 만들 수 있다.
4. 액션을 콘솔에 출력하거나, 서버 쪽에 로깅을 할 수 있다
5. 액션이 디스패치 됐을 때 이를 수정해서 리듀서에게 전달할 수 있다.
6. 특정 액션이 발생했을 때 이에 기반하여 다른 액션이 발생되도록 할 수 있다.
7. 특정 액션이 발생했을 때 특정 자바스크립트 함수를 실핼시킬 수도 있다.
const middleware = store => next => action => {
//하고싶은 작업 ....
}
function middleware(store){
return function(next){
return function(action){
//하고싶은 작업 .....
}
}
}
ContextAPI와 차별화되는 부분액션 ---> 미들웨어 ---> 리듀서 ---> 스토어
dispatch ({ type: "add_todo" })
redux-logger
const myLogger = store => next => action => {
//액션 출력하기
console.log(action);
//다음 미들웨어 (또는 리듀서) 에게 액션을 전달
const result = next(action);
//업데이트 이후의 상태를 출력
console.log(store.getState());
//여기에서 반환하는 result 값은 dispatch(action)의 결과물
return result;
}
export default myLogger;
redux-thunk --> 비동기전송
리덕스에서 미들웨어를 사용하는 주된 용도는 비동기 작업을 처리할 때앱에서 백엔드api를 연동해야할 때 리덕스 미들웨어로 처리한다
- 비동기 작업 관련된 리덕스 미들웨어 라이브러리
redux-thunk
redux-saga
redux-opsercable
redux-promise-middleware
redux middleware 설치
npm install redux
npm install react-redux둘 다 설치해줘야한다
react에서 redux 적용하기액션타입, 액션생성함수, 리듀서
const rootReducer = combineReducers({ counter: counter, todos: todos })
const store = createStore(rootReducer)
<Provider store={store}>
<App/>
</Provider>
const middleware = store=> next=> action => {
// 다음 middleware에게 액션을 전달
// 모든 middleware가 끝나면 reducer -> dispatch(action) 실행
const result= next(action);
// 여기에서 반환하는 result값은 dispatch(action)의 결과물
return result;
}
function middleware(store){
return function(next){
return function(action){
// 하고 싶은 작업
}
}
}
store : dispatch(), getState(), subscribe() 내장함수를 포함하고 있다.
next : 액션을 다음 미들웨어에게 전달하는 함수
action : 현재 처리하고 있는 액션객체
const store= createStore(rootReducer,applyMiddleware(middleware함수A, middleware함수B...));
createStore의 매개변수로applyMiddleware()를 입력한다.applyMiddleware의 매개변수로middleware를 입력하면 사용할 수 있다.