본문 바로가기
  • 삽질하는 자의 블로그
Redux, Redux-toolkit

4. Redux-ToolKit [다중 슬라이스 사용해보기]

by 이게뭐당가 2022. 12. 17.

 하나의 Slice 안에 관련 없는 State 와 Action 을 모두 넣을 수는 없다.

 

관련있는 것들끼리 모아 Slice 를 만들기 위해, 여러개의 Slice 를 사용해보자

 

연습할 프로세스

       [ 숫자를 세는 기능과, 로그인을 하는 기능이 들어간 웹이다]
        
        0. "로그인 상태" 는 "전역" 으로 관리되어야 하는 "State"이다 => 완벽한 redux 의 조건!
        1. 로그인이 되면, 네비게이션 바가 변경된다.
        2. 로그인 필드가 사라지고 새 컴포넌트가 반영된다.

        => State 를 추가해야한다. "counterSlice 와는 전혀 다른 동작의 State를"

        => 결국 "새 Slice 를 생성"하여, "로그인에 대한 State를 조작"해야한다.

        => 다중 Slice(State 관리) 가 필요하다

 

 

코드로 살펴보자

import { createSlice, configureStore } from "@reduxjs/toolkit";

const initialCounterState = { counter: 0, showCounter: true };
const initialAuthState = { Authentication: false };				// 새 초기값

const counterSlice = createSlice({
    name: "counter",
    initialState: initialCounterState,
    reducers: {
        increment(state) {
            state.counter++;
        },
        decrement(state) {
            state.counter--;
        },
        userinput(state, action) {
            state.counter = state.counter + action.payload;
        },
        toggleCounter(state) {
            state.showCounter = !state.showCounter;
        },
    },
});

const authSlice = createSlice({		// 새 리듀서
    name: "auth",
    initialState: initialAuthState,
    reducers: {
        login(state) {
            state.Authentication = true;
        },
        logout(state) {
            state.Authentication = false;
        },
    },
});

const store = configureStore({				// // 두개 이상의 Slice으로 store를 만든다.
    reducer: { counter: counterSlice.reducer, auth: authSlice.reducer },  // 객체를 생성해 key 안에 Slice의 reducer 를 넣는다.
});

export const counterAction = counterSlice.actions;

export const authAction = authSlice.actions;        // 마찬가지로 컴포넌트에서, 리듀서함수 사용을 위한 actions 을 export 한다.

export default store;

 

컴포넌트에서 사용해보자

import classes from "./Header.module.css";
import { useDispatch, useSelector } from "react-redux";      // 1. react와 redux 를 연결하는 dispatch 와 selector 을 불러온다.
import { authAction } from "../store/index";                 // 2. auth State 변경을 위한 authAction 을 불러오고

const Header = () => {
    const authState = useSelector((state) => state.auth.Authentication);   // ** 3. state 중, "Authentication" State를 불러온다.

    const authDispatch = useDispatch();                     // 4. dispatch 사용을 위한, useDispatch 를 호출한다.

    const logoutHandler = () => {
        authDispatch(authAction.logout());
    };

    return (
        <header className={classes.header}>
        <h1>Redux Auth</h1>
        <nav>
            <ul>
            <li>
                <a href="/">My Products</a>
            </li>
            <li>
                <a href="/">My Sales</a>
            </li>
            <li>
                {authState && <button onClick={logoutHandler}>Logout</button>}
            </li>
            </ul>
        </nav>
        </header>
    );
};

export default Header;

 

 

달라진 점은 하나다. State 를 가져올때, 가운데, 지정한 key 가 하나 더 끼는 것.

<기존의 store 저장>

const store = configureStore({
	reducer: auth: authSlice.reducer ,
});

< 다중 Slice 일때>

const store = configureStore({
	reducer: { counter: counterSlice.reducer, auth: authSlice.reducer }
});

		** "통합 reducer 가 [객체] 형식으로 지정되고 [key] 를 생성했으므로 "
        
< 기존의 State 호출 >

const authState = useSelector(state => state.authentication)

< 다중 Slice의 State 호출 >

const authState = useSelector(state => state.auth.authentication)

		** "State 호출시 [key] 에 접근하여, 참조한것이다.

 

댓글