simple diary : refactoring - context api

This commit is contained in:
haerong22
2022-04-15 21:08:21 +09:00
parent 8ecea4223a
commit e7ee23f938
3 changed files with 29 additions and 13 deletions

View File

@@ -36,9 +36,10 @@ const reducer = (state, action) => {
} }
}; };
const App = () => { export const DiaryStateContext = React.createContext();
// const [data, setData] = useState([]); export const DiaryDispatchContext = React.createContext();
const App = () => {
const [data, dispatch] = useReducer(reducer, []); const [data, dispatch] = useReducer(reducer, []);
const dataId = useRef(0); const dataId = useRef(0);
@@ -89,6 +90,10 @@ const App = () => {
dispatch({ type: "EDIT", targetId, newContent }); dispatch({ type: "EDIT", targetId, newContent });
}, []); }, []);
const memoizedDispatches = useMemo(() => {
return { onCreate, onRemove, onEdit };
}, []);
const getDiaryAnalysis = useMemo(() => { const getDiaryAnalysis = useMemo(() => {
const goodCount = data.filter((it) => it.emotion >= 3).length; const goodCount = data.filter((it) => it.emotion >= 3).length;
const badCount = data.length - goodCount; const badCount = data.length - goodCount;
@@ -99,14 +104,18 @@ const App = () => {
const { goodCount, badCount, goodRatio } = getDiaryAnalysis; const { goodCount, badCount, goodRatio } = getDiaryAnalysis;
return ( return (
<div className="App"> <DiaryStateContext.Provider value={data}>
<DiaryEditor onCreate={onCreate} /> <DiaryDispatchContext.Provider value={memoizedDispatches}>
<div>전체 일기 : {data.length}</div> <div className="App">
<div>기분 좋은 일기 : {goodCount}</div> <DiaryEditor />
<div>기분 나쁜 일기 : {badCount}</div> <div>전체 일기 : {data.length}</div>
<div>기분 좋은 일기 비율: {goodRatio} %</div> <div>기분 좋은 일기 : {goodCount}</div>
<DiaryList onEdit={onEdit} onRemove={onRemove} diaryList={data} /> <div>기분 나쁜 일기 : {badCount}</div>
</div> <div>기분 좋은 일기 비율: {goodRatio} %</div>
<DiaryList />
</div>
</DiaryDispatchContext.Provider>
</DiaryStateContext.Provider>
); );
}; };

View File

@@ -1,6 +1,9 @@
import React, { useRef, useState } from "react"; import React, { useContext, useRef, useState } from "react";
import { DiaryDispatchContext } from "./App";
const DiaryEditor = () => {
const { onCreate } = useContext(DiaryDispatchContext);
const DiaryEditor = ({ onCreate }) => {
const authorInput = useRef(); const authorInput = useRef();
const contentInput = useRef(); const contentInput = useRef();
const [state, setState] = useState({ const [state, setState] = useState({

View File

@@ -1,6 +1,10 @@
import { useContext } from "react";
import { DiaryDispatchContext, DiaryStateContext } from "./App";
import DiaryItem from "./DiaryItem"; import DiaryItem from "./DiaryItem";
const DiaryList = ({ onEdit, onRemove, diaryList }) => { const DiaryList = () => {
const diaryList = useContext(DiaryStateContext);
const { onEdit, onRemove } = useContext(DiaryDispatchContext);
return ( return (
<div className="DiaryList"> <div className="DiaryList">
<h2>일기 리스트</h2> <h2>일기 리스트</h2>