리덕스의 주요함수

Jean Young Park·2023년 3월 5일
0

react

목록 보기
14/32

createStore(reducer, [preloadedState], [enhancer])

  • 애플리케이션의 상태를 보관하는 store 객체를 생성한다.
  • reducer 함수를 전달하여 상태 변경을 처리하고, preloadedState를 전달하여 초기 상태를 설정할 수 있다.
  • enhancer 함수를 전달하여 미들웨어를 적용할 수 있다. ( ex. applyMiddleware )

    enhancer 함수란?
    createStore 함수가 반환하는 Store 객체를 커스터마이징 할 수 있는 함수로, 기본적인 Redux Store의 동작 방식을 변경하거나, 미들웨어를 추가하거나, 데브툴을 사용할 수 있게 해준다.

예시

import { createStore } from 'redux';

// 초기 상태 정의
const initialState = {
  count: 0
};

// 리듀서 함수 정의
function counterReducer(state = initialState, action) {
  switch (action.type) {
    case 'INCREMENT':
      return {
        ...state,
        count: state.count + 1
      };
    case 'DECREMENT':
      return {
        ...state,
        count: state.count - 1
      };
    default:
      return state;
  }
}

// createStore 함수를 사용하여 store 생성
const store = createStore(counterReducer);

combineReducers(reducers)

  • 여러 개의 reducer 함수를 하나로 합쳐준다.
  • 리듀서를 분리하여 관리할 수 있도록 해준다.

예시

import { createStore, combineReducers } from 'redux';

// counter 리듀서
function counterReducer(state = { count: 0 }, action) {
  switch (action.type) {
    case 'INCREMENT':
      return {
        ...state,
        count: state.count + 1
      };
    case 'DECREMENT':
      return {
        ...state,
        count: state.count - 1
      };
    default:
      return state;
  }
}

// todo 리듀서
function todoReducer(state = { items: [] }, action) {
  switch (action.type) {
    case 'ADD_TODO':
      return {
        ...state,
        items: [...state.items, action.payload]
      };
    case 'REMOVE_TODO':
      return {
        ...state,
        items: state.items.filter((item) => item.id !== action.payload.id)
      };
    default:
      return state;
  }
}

// 여러 개의 리듀서를 combineReducers 함수를 사용하여 합치기
const rootReducer = combineReducers({
  counter: counterReducer,
  todo: todoReducer
});

// createStore 함수를 사용하여 store 생성
const store = createStore(rootReducer);

applyMiddleware(...middlewares)

  • 리덕스 미들웨어를 적용한다.
  • 미들웨어는 액션을 디스패치하기 전후로 추가적인 작업을 수행할 수 있다.

예시

import { createStore, applyMiddleware } from 'redux';
import logger from 'redux-logger';
import thunk from 'redux-thunk';
import promiseMiddleware from 'redux-promise-middleware';
import rootReducer from './reducers';

// applyMiddleware 함수를 사용하여 미들웨어 적용
const store = createStore(
  rootReducer,
  applyMiddleware(thunk, promiseMiddleware, logger)
);

리덕스 미들웨어란? (클릭)

bindActionCreators(actionCreators, dispatch)

  • 액션 생성자 함수를 디스패치할 수 있는 함수로 변환한다.
  • 액션 생성자 함수를 호출할 때마다 액션을 디스패치하는 작업을 수행하지 않아도 된다.

예시

import { bindActionCreators } from 'redux';
import { increaseCount, decreaseCount } from './actions';

// 액션 생성자 함수를 전달하여 bindActionCreators 함수를 호출
const actions = bindActionCreators({
  increaseCount,
  decreaseCount,
}, dispatch);

// actions 객체를 컴포넌트 props로 전달하여 사용
// 이제 increaseCount()와 decreaseCount()는 자동으로 dispatch 됩니다.
<MyComponent {...actions} />

import React from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { increaseCount } from './actions';

function MyComponent(props) {
  return (
    <div>
      <button onClick={props.increaseCount}>Increase</button>
    </div>
  );
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators({ increaseCount }, dispatch);
}

export default connect(null, mapDispatchToProps)(MyComponent);

( 이 내용도 좀 더 다뤄봐야 될 것 같다... )

getState()

  • 현재 상태를 반환한다.

예시

import { createStore } from 'redux';

// reducer
function counter(state = { count: 0 }, action) {
  switch (action.type) {
    case 'INCREMENT':
      return { count: state.count + 1 };
    case 'DECREMENT':
      return { count: state.count - 1 };
    default:
      return state;
  }
}

// store 생성
const store = createStore(counter);

// getState() 사용 예시
console.log(store.getState()); // { count: 0 }

subscribe(listener)

  • 상태가 변경될 때마다 호출되는 콜백 함수를 등록한다.
  • 상태 변경을 감지하여 UI를 업데이트 할 수 있도록 해준다.

예시

import { createStore } from 'redux';

// 초기 상태
const initialState = {
  count: 0,
};

// 리듀서 함수
function counter(state = initialState, action) {
  switch (action.type) {
    case 'INCREMENT':
      return { count: state.count + 1 };
    case 'DECREMENT':
      return { count: state.count - 1 };
    default:
      return state;
  }
}

// 스토어 생성
const store = createStore(counter);

// subscribe 함수를 이용한 상태 변화 모니터링
store.subscribe(() => {
  console.log(store.getState());
});

// 액션 디스패치
store.dispatch({ type: 'INCREMENT' });
store.dispatch({ type: 'INCREMENT' });
store.dispatch({ type: 'DECREMENT' });

dispatch(action)

  • 액션을 디스패치한다.
  • 액션이 디스패지되면 리듀서가 호출되어 상태를 변경한다.

예시

import { createStore } from 'redux';

// 리덕스에서 관리할 초기 상태값
const initialState = {
  count: 0,
};

// 액션 타입 상수
const INCREASE = 'INCREASE';
const DECREASE = 'DECREASE';

// 액션 생성자 함수
function increaseAction() {
  return { type: INCREASE };
}

function decreaseAction() {
  return { type: DECREASE };
}

// 리듀서 함수
function counter(state = initialState, action) {
  switch (action.type) {
    case INCREASE:
      return { count: state.count + 1 };
    case DECREASE:
      return { count: state.count - 1 };
    default:
      return state;
  }
}

// 스토어 생성
const store = createStore(counter);

// dispatch 함수 사용 예시
store.dispatch(increaseAction()); // { count: 1 }
store.dispatch(decreaseAction()); // { count: 0 }
store.dispatch(increaseAction()); // { count: 1 }

0개의 댓글