본문 바로가기

[React]

React-02(Redux)

반응형

React

리액트의 꽃 Redux(리덕스)

  • 리덕스란? : 상태 관리 라이브러리로써 React뿐만이 아닌 jquery, vue.js, Augular.js와도 충분히 사용가능
    ex) 컴포넌트에서는 useState, props를 통해 관리하였는데 todo리스트의 경우
    const state = { todoList: [], doneList: [], deleteList: [], }
    와 같이 관리하는 것이 복잡해 질 수 있다.
    이것을 redux에서는 글로벌로 관리가 가능하다.

  • 사용방법은? : 리덕스가 적용된 react를 이용하기위해서는 npx create-react-app my-app --template redux또는 기존 react 앱에서 yarn add react-redux를 통해 추가 가능하다.

  • redux 기본 사이클 개념

    1. dispatch : 디스패치 함수를 실행하면
    2. action : 액션이 발생한다.
    3. reducer : 이를 리듀서가 전달하면
    4. state : 최종적으로 상태를 바꾼다.
  • redux 기초 용어 개념

    • action : {type:'some text'}
    • reducer : function reducer(state, action){return changeState}
    • store : 앱에는 단 하나의 스토어가 존재함. (현재 상태, 리듀서가 포함됨.)
    • dispatch : 스토어 내장 함수로, 액션을 발생시키는 함수다.(ex. dispatch(action))

기존React에 Redux 추가해서 이용하기

  1. npx create-react-app my-app 기존 프로젝트 생성

  2. yarn add react-redux 리덕스 추가

  3. src 폴더 하위에 modules 폴더 생성, modules 폴더 안에 상태관리할 컴포넌트들 생성

  4. src 폴더 하위에 index.js 생성, modules 폴더 내부에 있는 컴포넌트들을 모두 관리.

  5. 크롬에서 redux 상태를 쉽게 관리하기 위해 크롬확장프로그램 Redux DevTools를 설치하면 유용함.
    개발자 도구 탭에서 redux 탭이 생겨서 여기서 관리 가능
    (공식 문서 : https://github.com/reduxjs/redux-devtools/tree/main/extension#installation)

    1. 크롬 개발자 도구 설치

    2. src/index.js에서 store을 추가한 부분에
      window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__() 추가

      const store = createStore(
          rootReducer,
          window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
      )

      EX)
      store/moduels/todo.js

      // 우리가 원하는 행동, 데이터의 변화를 가각의 액션으로 할당
      
      // 액션 타입(문자열)
      const CREATE = 'todo/CREATE' // 할 일 목록을 추가하는 액션
      const DONE = 'todo/DONE' // 할 일 목록 중에서 완료 처리 하는 것
      
      // 액션 생성 함수
      export function create(payload) {
      return {
          type: CREATE,
          payload: payload,
      }
      }
      
      export function done(id) {
      return {
          type: DONE,
          id: id,
      }
      }
      
      // 초기 상태
      const initState = {
      list: [
          {
          id: 0,
          text: '척추 펴기',
          done: true,
          },
          {
          id: 1,
          text: '물 마시기',
          done: false,
          },
      ],
      }
      
      // 리듀서
      export default function toto(state = initState, action) {
      switch (action.type) {
          case CREATE:
          return {
              ...state,
              list: state.list.concat({
              id: action.payload.id,
              text: action.payload.text,
              done: false,
              }),
          }
          case DONE:
          return {
              ...state,
              list: state.list.map((item) => {
              return item.id === action.id ? { ...item, done: true } : item
              }),
          }
          default:
          return state
      }
      }
      

      store/index.js

      import { combineReducers } from 'redux'
      import todo from './modules/todo'
      
      export default combineReducers({
      todo, //서브 리듀서
      })

      ``

      src/index.js

      import React from 'react'
      import ReactDOM from 'react-dom'
      import './index.css'
      import App from './App'
      import reportWebVitals from './reportWebVitals'
      
      //리덕스를 위한 코드들
      import { createStore } from 'redux'
      import rootReducer from './store'
      import { Provider } from 'react-redux'
      
      const store = createStore(rootReducer)
      
      ReactDOM.render(
      <React.StrictMode>
          <Provider store={store}>
          <App />
          </Provider>
      </React.StrictMode>,
      document.getElementById('root')
      )
      
      reportWebVitals()
  6. 컴포넌트에서 상태 가져와서 이용하기.

    • 읽기
      import { useSelector } from 'react-redux'
      const list = useSelector((state) => state.todo.list)
    • 쓰기(버튼 클릭하면 쓰게 만들었음.)
      import { useDispatch, useSelector } from 'react-redux'
      const dispatch = useDispatch()
      <button
              onClick={() => {
              dispatch(create({ id: list.length, text: inputRef.current.value }))
              }}
      >
              확인
      </button>

(관련 글, 리덕스 이용해 TodoList 만들기 : https://github.com/ppojun/redux-todoList)

반응형

'[React]' 카테고리의 다른 글

React-01(기초)  (0) 2022.04.10