리액트-유저모듈만들기 개념편

양송현·2021년 10월 12일
0

리덕스는 덕스구조로 되어있음. (아닌 경우도 있음)

덕스구조 : 액션타입,액션함수,리듀서,initialState(기본값)이 한파일에 담겨있는 구조

덕스구조의 모듈을 만들기 위해 여러 패키지를 깔아야 함.

2021.03 기준임

immer사용
yarn add immer redux-actions

리덕스에서 history 쓸 수 있게 해주는 패키지
yarn add redux react-redux redux-thunk redux-logger history@4.10.1 connected-react-router@6.8.0

리덕스 파일,폴더 생성 (나름 트리구조로 설명한것임!)

SRC >
    > redux(폴더생성) 
        > modules(폴더생성)
    	    >user.js (파일생성)
    > configureStore.js(파일생성)

실재 생성된 파일

덕스구조 소스 구성

[user.js]

import {createAction, handleActions} from "redux-actions"; // createAction: 액션을 편하게 만들어줌 / handleActions: 리듀서를 편하게 만들어줌
import {produce} from "immer"; // 불변성 관리 편하게 해줌 (불변성 : 어떤값을 직접적으로 변경하지 않고 새로운 값으로 복사하는 것)

//actions (액션타입)
const LOG_IN = "LOG_IN";
const LOG_OUT = "LOG_OUT";
const GET_USER = "GET_USER";

// action creators
const logIn = createAction(LOG_IN, (user)       =>      ({user})); 
                          //타입   파라미터값을 (리듀서에게) 넘겨줌


// reducer
const reducer = handleActions({

[LOG_IN]: (state, action) => {
// 여기에다가 어떤 액션에 대한 내용인지 바로 씀. 액션이 바뀔경우도 쭉쭉 쓰면됨.
}
},      {});
// initialState 써주는 부분

주석 충 컨셉으로 설명했으니 주석을 많이많이 봐주시길 바랍니다.
개념을 이해 했으니 이제 쭉쭉 소스코드를 작성하겠습니다.

import {createAction, handleActions} from "redux-actions";
import {produce} from "immer";
import {setCookie, getCookie, deleteCookie} from "../../shared/Cookie"

//actions (액션타입)
const LOG_IN = "LOG_IN";
const LOG_OUT = "LOG_OUT";
const GET_USER = "GET_USER";

// action creators
const logIn = createAction(LOG_IN, (user) => ({user})); 
const logOut = createAction(LOG_OUT, (user) => ({user}));
const getUser = createAction(GET_USER, (user) => ({user}));


// initialState
const initialState = {
    user: null,
    is_login: false,

}

// reducer
export default handleActions({

    [LOG_IN]: (state, action) => produce(state, (draft) => {
        setCookie("is_login", "success");
        draft.user = action.payload.user;
        draft.is_login = true;
    }),
    [LOG_OUT]: (state, action) => produce(state, (draft) => {}),
    [GET_USER]: (state, action) => produce(state, (draft) => {}),
    
    },
    initialState
);

// action creator export
const actionCreators = {
    logIn,
    logOut,
    getUser
};

이제 뭐해야된다? 스토어 만들어 줘야한다.

profile
코린이의 뽀짝한 블로그

0개의 댓글