ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Redux] 아주 아주 간단한 리덕스 기본 개념 2
    개발/React 2022. 7. 8. 14:46

    리액트에서 사용하기 위한 기본 준비를 해봅시다.

    Ducks 패턴이란 걸 사용할 겁니다.

    아주 간단한 패턴이에요.

     

    https://github.com/erikras/ducks-modular-redux

     

    액션 타입, 액션 생성 함수, 리듀서를 각각의 파일로 분리하지 않고

    파일 하나에 모아 모듈화하는 걸 말합니다.

    이 패턴에서는 그렇게 모아둔 파일을 모듈이라고 해요.

    자세한 설명은 위의 주소에서 확인할 수 있습니다.

     

    덕스 패턴엔 규칙 몇 가지가 있습니다.

    1. MUST 리듀서 함수는 export default로 내보낼 것

    2. MUST 액션 생성 함수를 export 할 것

    3. MUST 액션 타입은 reducer/ACTION_TYPE의 형식을 취할 것

    4. MAY 액션 타입은 UPPER_SNAKE_CASE를 사용할 것

     

    이렇게 모듈화한 리듀서는 일종의 서브 리듀서가 되며

    리덕스 패키지에 있는 combineReducers 함수를 이용해 rootReducer를 만들어서 사용합니다.

    다음 파일들은 modules 폴더에 있습니다.

     

    counter.js

    const SET_DIFF = 'counter/SET_DIFF';
    const INCREASE = 'counter/INCREASE';
    const DECREASE = 'counter/DECREASE';
    
    export const setDiff = (diff) => ({ type: SET_DIFF, diff });
    export const increase = () => ({ type: INCREASE });
    export const decrease = () => ({ type: DECREASE });
    
    const initialState = {
      number: 0,
      diff: 1,
    };
    
    export default function counter(state = initialState, action) {
      switch (action.type) {
        case SET_DIFF:
          return {
            ...state,
            diff: action.diff,
          };
        case INCREASE:
          return {
            ...state,
            number: state.number + action.diff,
          };
        case DECREASE:
          return {
            ...state,
            number: state.number - action.diff,
          };
        default:
          return state;
      }
    }

     

    todos.js

    const ADD_TODO = 'todos/ADD_TODOS';
    const TOGGLE_TODO = 'todos/TOGGLE_TODO';
    
    let nextId = 1;
    export const addTodo = (text) => ({
      type: ADD_TODO,
      todo: {
        id: nextId++,
        text,
      },
    });
    
    export const toggleTodo = (id) => ({
      type: TOGGLE_TODO,
      id,
    });
    
    const initialState = [
      /*
        {
            id: 1,
            text: 'text',
            done: false
            
        }
      */
    ];
    
    export default function todos(state = initialState, action) {
      switch (action.type) {
        case ADD_TODO:
          return state.concat(action.todo);
        case TOGGLE_TODO:
          return state.map((todo) =>
            todo.id === action.id ? { ...todo, done: !todo.done } : todo
          );
        default:
          return state;
      }
    }

     

    index.js

    import { combineReducers } from 'redux';
    import counter from './counter';
    import todos from './todos';
    
    const rootReducer = combineReducers({
      counter,
      todos,
    });
    
    export default rootReducer;

     

    리듀서를 리액트 앱에 적용할 때는 react-redux 패키지의 Provider 함수로 감싸주며

    props로 store를 넘겨주면 됩니다.

    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 { legacy_createStore as createStore } from 'redux';
    import rootReducer from './modules';
    
    const store = createStore(rootReducer);
    console.log(store.getState());
    
    const root = ReactDOM.createRoot(document.getElementById('root'));
    root.render(
      <Provider store={store}>
        <React.StrictMode>
          <App />
        </React.StrictMode>
      </Provider>
    );

     

    참고

    https://redux.vlpt.us/4-1-ducks.html

    벨로퍼트 리액트 강의

    댓글

Designed by Tistory.