ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • React redux (toolkit) 간단 사용법
    DEV/react 2025. 1. 22. 16:04

    1. install

    npm install redux react-redux @reduxjs/toolkit

     

     

    2. src > redux 폴더 생성 > store.js 생성 (src/redux/store.js)

    import React from 'react';
    import { configureStore } from '@reduxjs/toolkit';
    
    export default configureStore({
      reducer: {},
    });

     

     

    3. index.js (파일명은 다를 수 있으나 리엑트의 시작점 파일을 찾아가자)

    <App />을 <Provider store={store}>로 감싸주자.

    import { StrictMode } from 'react'
    import { createRoot } from 'react-dom/client'
    import './index.css'
    import App from './App.jsx'
    import { Provider } from 'react-redux'
    import store from './redux/store.js'
    
    createRoot(document.getElementById('root')).render(
      <StrictMode>
        <Provider store={store}>
          <App />
        </Provider>
      </StrictMode>,
    )

     

    4. reducer 생성 (src/redux/controller.js)

    나는 Controller라는 reducer를 생성해보겠다.

    controller.js

    import { createSlice } from '@reduxjs/toolkit'
    
    export const controllerSlice = createSlice({
      name: "controller",	// reducer 이름
      initialState: {		// 초기값
        value: {
          up: false,
          down: false,
          left: false,
          right: false,
          confirm: false,
        }
      },
      reducers: {			// 상태가 변하면 진행할 행동
        move: (state, action) => {
          state.value = action.payload;
        }
      }
    })
    
    // 나 move 쓸꺼임
    export const { move } = controllerSlice.actions;
    // reducer export
    export default controllerSlice.reducer;

     

    5. store에 생성된 reducer를 저장

     

    store.js

    import { configureStore } from '@reduxjs/toolkit';
    import controllerReducer from './controller';
    
    export default configureStore({
      reducer: {
        controller: controllerReducer,
      },
    });

     

    6. 아무 컴포넌트에서 해당 초기값을 잘 불러오는지 확인

    import React, { useEffect } from 'react'
    import { useSelector } from 'react-redux';
    
    function Controller() {
      // 생성한 redux controller
      const controller = useSelector((state) => state.controller.value);
      
      // useSeletor로 불러온 controller값을 출력
      useEffect(()=> {
        console.log("controller : ", controller);
      }, [controller])
    
      return (
        <div className="controller-container">
          <div className="controller upper-controller">
            // 컴포넌트 내용 생략...
          </div>
        </div>
      );
    }
    
    export default Controller;

     

    잘 불러온다.

     

    7. 업데이트 해보자.

     

    특정 키를 누르면 해당 값(bool)의 반대 값으로 저장해보자.

    import React, { useEffect } from 'react'
    import { useDispatch, useSelector } from 'react-redux';
    import { move } from '../redux/controller';
    
    function Controller() {
      const dispatch = useDispatch();
      const current = useSelector((state) => state.controller.value);
    
      const controllerEvent = (key) => {
        switch (key) {
          case 'up':
            dispatch(move({up: !current.up}));
            break;
          case 'down':
            dispatch(move({down: !current.down}));
            break;
          case 'left':
            dispatch(move({left: !current.left}));
            break;
          case 'right':
            dispatch(move({right: !current.right}));
            break;
          case 'confirm':
            dispatch(move({confirm: !current.confirm}));
            break;
        }
      }
    
      useEffect(()=>{
        console.log("controller : ", current);
      }, [current])
    
      return (
        <div className="controller-container">
          <div className="controller upper-controller">
            <div className="inner-controller">
    
            </div>
            <div
              className="inner-controller"
              onClick={() => controllerEvent('up')}
            >
              ▲
            </div>
            <div className="inner-controller">
    
            </div>
          </div>
    
          <div className="controller center-controller">
            <div
              className="inner-controller"
              onClick={() => controllerEvent('left')}
            >
              ◀
            </div>
            <div
              className="inner-controller controller-center"
              onClick={() => controllerEvent('confirm')}
            >
              ⦁
            </div>
            <div
              className="inner-controller"
              onClick={() => controllerEvent('right')}
            >
              ▶
            </div>
          </div>
    
          <div className="controller bottom-controller">
            <div className="inner-controller">
    
            </div>
            <div
              className="inner-controller"
              onClick={() => controllerEvent('down')}
            >
              ▼
            </div>
            <div className="inner-controller">
    
            </div>
    
          </div>
        </div>
      );
    }
    
    export default Controller;

    굿

     

    댓글

Designed by Tistory.