리덕스(Redux)

Min·2021년 1월 4일
0

REACT

목록 보기
5/18
post-thumbnail

리덕스(Redux)

  • predictable state container for JS apps
  • state 상태 관리 library

출처: 더 알아보기

  • 예를 들어 댓글을 관리하는 component 중 하위 component에서 변경이 일어나면
    그 변경된 값이 상위 component를 타고 올라가야 한다.
    그러나 redux를 이용하면 외부의 store를 통해 변경된 지점에서 직접 정보를 주고받을 수 있다.

  • 한 방향으로 흐른다.

리덕스(Redux) 설치

npm install redux react-redux redux-promise redux-thunk --save

  • action이 object(객체)형식 이어야 store가 받을 수 있다.
    그런데, store에서 언제나 object 형태의 action만 받는 것은 아니다.

  • promise , function 형태로도 온다.
    그럴 때 redux의 middleware인 Redux-promise / Redux-thunk 가 필요하다.
    - Redux-promise : dispatch에게 어떻게 promise를 받는지 알려준다.
    - Redux-thunk : dispatch에게 어떻게 function을 받는지 알려준다.

  • Redux DevTools : chrome webstore에서 확장 프로그램 다운로드

Action

  • 무엇이 일어났는지 설명하는(상태를 알려주는) 객체

Reducer

  • 기존 state값이 action으로 인해 다른 state 값으로 바뀌었다는 것을 설명해주는 곳

Store

  • 전체적인 application의 state를 감싸주는 역할
  • store 내의 여러 method를 통해 state을 관리할 수 있다.

CombineReducer

⭐ client/src/index.js
import React from 'react'
import ReactDOM from 'react-dom'
import './index.css'
import App from './App'
import * as serviceWorker from './serviceWorker'
import { Provider } from 'react-redux'

// redux에서 제공하는 Provider로 redux를 우리 App에 연결
import 'antd/dist/antd.css'
import { applyMiddleware, createStore } from 'redux'

// applyMiddleware, createStore method를 redux에서 가져옴.
import promiseMiddleware from 'redux-promise'
import ReduxThunk from 'redux-thunk'
import Reducer from './_reducers'

⭐ src/_reducers/index.js에 정의한 reducer을 가져옴
const createStoreWithMiddleware = applyMiddleware(promiseMiddleware, ReduxThunk)(createStore)

// object뿐 아니라 promise, function을 모두 받기 위해 redux-promise, redux-thunk을 가져와 redux에서 store생성 
ReactDOM.render(

  <Provider
   store={createStoreWithMiddleware(Reducer,
    window.__REDUX_DEVTOOLS_EXTENSION__ &&
    window.__REDUX_DEVTOOLS_EXTENSION__()
    )}
    
  // 위에서 만든 store를 store에 넣었다.
  // web에서 받은 redux 확장프로그램 삽입
  
  >
    <App />
  </Provider>
  
  // App을 Provider로 감쌈.  
  , document.getElementById('root')
)

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister()

⭐ client/src/_reducers/index.js
import { combineReducers } from 'redux'
// store 안에는 user reducer, comment reducer 등 수많은 reducer들이 있다.
// combine reducer는 그것들을 묶어 root reducer에서 하나로 합쳐준다.
// import user from './user_reducer';

const rootReducer = combineReducers({
    // user, comment
})

export default rootReducer

참고 강의
참고 칼럼

profile
slowly but surely

0개의 댓글