Notice
Recent Posts
Recent Comments
«   2025/06   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Archives
Today
Total
관리 메뉴

AI기록장

React_기초다지기_하루정리(useReducer) 본문

React

React_기초다지기_하루정리(useReducer)

SanL 2023. 6. 4. 20:04

◼︎React


⚑목표 : 실습 기초 세팅

  1. 상태 관리 세팅하기
    : 프로젝트 전반적으로 사용될 일기 데이터 state관리 로직 작성하기
  2. 프로젝트 State Context세팅하기
    : 일기 데잍 State를 공급할 context를 생성하고 Provider로 공급하기
  3. 프로젝트 Dispatch Context 세팅하기
    : 일기 데이터 Statedml Dispatch 함수들을 공급할 Context를 생성하고 Provider로 공급하기


import React, { useReducer, useRef } from "react";

import "./App.css";
import { BrowserRouter, Route, Routes } from "react-router-dom";

import Home from "./pages/Home";
import Edit from "./pages/Edit";
import New from "./pages/New";
import Diary from "./pages/Diary";

const reducer = (state, actions) => {
  let newState = [];
  switch (actions.type) {
    case "INIT": {
      return actions.data;
    }
    case "CREATE": {
      newState = [actions.data, ...state];
      break;
    }
    case "REMOVED": {
      newState = state.filter((it) => it.id !== actions.targetId);
      break;
    }
    case "EDIT": {
      newState = state.map((it) =>
        it.id === actions.data.id ? { ...actions.data } : it
      );
      break;
    }
    default:
      return state;
  }
  return newState;
};

export const DiaryStateContext = React.createContext();
export const DiaryDispatchContext = React.createContext();

function App() {
  const [data, dispatch] = useReducer(reducer, []);

  const dataId = useRef(0); // id를 만들어줌

  //정보를 파라미터로받아서 객체로 만들고 그것을 creat로 저장함
  const onCreate = (date, content, emotion) => {
    dispatch({
      type: "CREATE",
      data: {
        id: dataId.current,
        date: new Date(date).getTime(),
        content,
        emotion,
      },
    });

    dataId.current += 1;
  };

  const onRemove = (targetId) => {
    dispatch({ type: "REMOVE", targetId });
  };

  const onEdit = (targetId, date, content, emotion) => {
    dispatch({
      type: "EDIT",
      data: {
        id: targetId,
        date: new Date(date).getTime(),
        content,
        emotion,
      },
    });
  };

  return (
    <DiaryStateContext.Provider value={data}>
      <DiaryDispatchContext.Provider
        value={{
          onCreate,
          onEdit,
          onRemove,
        }}>
        <BrowserRouter>
          <div className="App">
            <Routes>
              <Route path="/" element={<Home />} />
              <Route path="/new" element={<New />} />
              <Route path="/edit" element={<Edit />} />
              <Route path="/diary/:id" element={<Diary />} />
            </Routes>
          </div>
        </BrowserRouter>
      </DiaryDispatchContext.Provider>
    </DiaryStateContext.Provider>
  );
}

export default App;
//클라이언트 사이드 랜더링 기법을 이용함

  • 이번 페이지는 크게 설명할꺼는 없지만, 저번시간의 코드들을 useReducer을 이용해서 코드 업데이트를 했다!
    // 아직 useReducer을 사용하는데 있어 낯선감이 있어, 아직 코드의 관계를 빠르게 이해를 못하겠다!
    이부분은 useReducer을 한번 더 이해하고, 각각의 프롭스의 관계를 다시 정리해봐야겠다.