ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • #3-4 불변성과 리듀서 여러개 합치기
    React로 nodebirdSNS 만들기 (인프런)/#3 리덕스 익히기 2020. 1. 8. 13:01
    • ...state를 쓴 이유는 불변성 때문이다.
      • state는 어떠한 이유에서든 절대 변해서는 안된다. 리액트에선 setState를 사용했음

    - front폴더->reducers폴더->index.js

      - user.js, post.js파일에있는 reducers들을 하나로 합친것 (중앙통제시스템)

    import { combineReducers } from "redux";
    import user from "./user";
    import post from "./post";
    
    const rootReducer = combineReducers({
      user,
      post
    });
    
    export default rootReducer;
    

    - user.js

    // store (state)
    export const initialState = {
      isLoggedIn: false,
      user: {}
    };
    
    const LOG_IN = "LOG_IN"; // 액션의 이름
    const LOG_OUT = "LOG_OUT";
    
    // 실제 액션과 데이터
    const loginAction = {
      type: LOG_IN,
      data: {
        nickname: "정중식"
      }
    };
    
    const logoutAction = {
      type: LOG_OUT
    };
    
    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
          };
        }
      }
    };
    
    export default reducer;
    

    - post.js

    export const initialState = {
      mainPosts: []
    };
    
    const ADD_POST = "ADD_POST";
    const ADD_DUMMY = "ADD_DUMMY";
    
    const addPost = {
      type: ADD_POST
    };
    const addDummy = {
      type: ADD_DUMMY,
      data: {
        content: "Hello",
        UserId: 1,
        User: {
          nickname: "정중식"
        }
      }
    };
    
    const reducer = (state = initialState, action) => {
      switch (action.type) {
        case ADD_POST: {
          return {
            ...state
          };
        }
        case ADD_DUMMY: {
          return {
            ...state,
            mainPosts: [action.data, ...state.mainPosts]
          };
        }
      }
    };
    
    export default reducer;
    

    댓글

Designed by Tistory.