React로 SNS만들기 03-2 Redux 연동하기

onezeun·2022년 3월 1일

React로 SNS만들기

목록 보기
7/11

4. 미들웨어와 리덕스 데브툴즈

미들웨어

액션을 기록하고 싶다? → 미들웨어 붙이기

설치

npm i redux-devtools-extension

브라우저 개발자도구와 연동하기 할 수 있음


reducers/index.js

import { HYDRATE } from "next-redux-wrapper";

...
const reducer = (state = initialState, action) => {
  switch (action.type) {
    case HYDRATE:
      return { ...state, ...action.payload };
      ...
  }
};

store/configureStore.js

import { applyMiddleware, compose, createStore } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension';

const configureStore = () => {
  const middlewares = [];
  const enhancer = process.env.NODE_ENV === 'production'
    ? compose(applyMiddleware(...middlewares))
    : composeWithDevTools(applyMiddleware(...middlewares),
    );
  const store = createStore(reducer, enhancer);
  return store;
};
...

데브툴즈 사용


개발자 도구에서 액션 실행 히스토리, 데이터가 어떻게 바뀌는지 확인 가능

  • State : 전체상태 확인
  • Diff : 뭐가 바뀌었는지 확인

관리 하기 쉽고 JUMP나 SKIP도 가능하당
디버깅할때 편함

5. 리듀서 쪼개기

initialState 기준으로 쪼개자 . .

ㅋㅋ;;

reducer의 기본 형태

const initialState = {

}

const reducer = (state = initialState, action) => {
  switch (action.type) {
    default:
      return state;
  }
}

export default reducer;

user, post 쪼개기

reducers/post.js


export const initialState = {
  mainPosts: [],
}

const reducer = (state = initialState, action) => {
  switch (action.type) {
    default:
      return state;
  }
}

export default reducer;

reducers/user.js

// 초기상태
export const initialState = {
  isLoggedIn: false,
  user: null,
  signUpData: {},
  loginData: {},
};

// 액션
export const loginAction = (data) => {
  return {
    type: 'LOG_IN',
    data,
  };
};

export const logoutAction = (data) => {
  return {
    type: 'LOG_OUT',
    data,
  };
};

// (이전상태, 액션) => 다음상태
const reducer = (state = initialState, action) => {
  switch (action.type) {
    case 'LOG_IN':
      return {
        ...state,
        isLoggedIn: true,
        user: action.data,
      };
    case 'LOG_OUT':
      return {
        ...state,
        isLoggedIn: false,
        user: null,
      };
    default:
      return state;
  }
};

export default reducer;

index에서 합치기

reducer는 함수이기 때문에 합치기 쉽지 않음 그래서 combineReducers를 사용해 합침

reducers/index.js


import { HYDRATE } from 'next-redux-wrapper';
import { combineReducers } from 'redux';

import user from './user';
import post from './post';


// (이전상태, 액션) => 다음상태
const reducer = combineReducers({
  index: (state = {}, action) => {
    switch (action.type) {
      case HYDRATE:
        return { ...state, ...action.payload };
      default:
        return state;
    }
},
  user,
  post,
});

export default reducer;

HYDRATE를 사용하기 위해 . .

index: (state = {}, action) => {
  switch (action.type) {
    case HYDRATE:
      return { ...state, ...action.payload };
    default:
      return state;
  }
},

SSR을 위해 이 부분을 넣어줘야 한당

쪼갤 때 경로 신경쓰기

profile
엉망진창

0개의 댓글