재밌고 어려운 IT를 이해해보자~!
Middleware, Redux thunk, promise 본문
미들웨어란
미들웨어는, 액션이 디스패치(dispatch) 되어서 리듀서에서 이를 처리하기전에 사전에 지정된 작업들을 설정한다.
미들웨어를 액션과 리듀서 사이의 중간자이다.
Redux-thunk
리덕스를 사용하는 어플리케이션에서 비동기 작업을 처리 할 때 가장 기본적인 방법으로는 redux-thunk 라는 미들웨어를 사용하는것이다. 이 미들웨어는 리덕스를 개발한 Dan Abramov 가 만든 것이며, redux 공식 매뉴얼에서도 이 미들웨어를 사용하여 비동기 작업을 다룬다. 이를 사용하여 비동기 작업을 관리하는건 매우 직관적이고 간단
이 미들웨어는 객체 대신 함수를 생성하는 액션 생성함수를 작성 할 수 있게 해준다.
리덕스에서는 기본적으로는 액션 객체를 디스패치한다.
일반 액션 생성자는, 다음과 같이 파라미터를 가지고 액션 객체를 생성하는 작업만한다.
만약에 특정 액션이 몇초뒤에 실행되게 하거나, 현재 상태에 따라 아예 액션이 무시되게 하려면, 일반 액션 생성자로는 할 수가 없다. 하지만, redux-thunk 는 이를 가능하게한다!
Redux-promise
이 미들웨어는 프로미스 기반의 비동기 작업을 조금 더 편하게 해주는 미들웨어이다.
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import {Provider } from 'react-redux';
import 'antd/dist/antd.css';
import promiseMiddleware from 'redux-promise';
import ReduxThunk from 'redux-thunk';
import Reducer from './_reducers/';
const creatStoreWithMiddleware = applyMiddleware(promiseMiddleware, ReduxThunk)(createStroe)
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<Provider
store={creatStoreWithMiddleware(Reducer,
window.__REDUX_DEVTOOLS_EXTENSION__ &&
window.__REDUX_DEVTOOLS_EXTENSION__()
)}
>
<App />
</Provider>
</React.StrictMode>
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
import { combineReducesrs } from 'redux';
// import user from './user.reducer';
const rootReducer = combineReducers({
// user,
})
export default rootReducer;
'React, Node Js' 카테고리의 다른 글
LoginPage with React -1 (0) | 2024.05.24 |
---|---|
React Hook (0) | 2024.05.23 |
Ant Design, Redux (0) | 2024.05.16 |
Concurrently (0) | 2024.05.15 |
데이터 Flow & Axios (0) | 2024.05.13 |
Comments