simple diary : refactoring - context api
This commit is contained in:
@@ -36,9 +36,10 @@ const reducer = (state, action) => {
|
||||
}
|
||||
};
|
||||
|
||||
const App = () => {
|
||||
// const [data, setData] = useState([]);
|
||||
export const DiaryStateContext = React.createContext();
|
||||
export const DiaryDispatchContext = React.createContext();
|
||||
|
||||
const App = () => {
|
||||
const [data, dispatch] = useReducer(reducer, []);
|
||||
|
||||
const dataId = useRef(0);
|
||||
@@ -89,6 +90,10 @@ const App = () => {
|
||||
dispatch({ type: "EDIT", targetId, newContent });
|
||||
}, []);
|
||||
|
||||
const memoizedDispatches = useMemo(() => {
|
||||
return { onCreate, onRemove, onEdit };
|
||||
}, []);
|
||||
|
||||
const getDiaryAnalysis = useMemo(() => {
|
||||
const goodCount = data.filter((it) => it.emotion >= 3).length;
|
||||
const badCount = data.length - goodCount;
|
||||
@@ -99,14 +104,18 @@ const App = () => {
|
||||
const { goodCount, badCount, goodRatio } = getDiaryAnalysis;
|
||||
|
||||
return (
|
||||
<div className="App">
|
||||
<DiaryEditor onCreate={onCreate} />
|
||||
<div>전체 일기 : {data.length}</div>
|
||||
<div>기분 좋은 일기 : {goodCount}</div>
|
||||
<div>기분 나쁜 일기 : {badCount}</div>
|
||||
<div>기분 좋은 일기 비율: {goodRatio} %</div>
|
||||
<DiaryList onEdit={onEdit} onRemove={onRemove} diaryList={data} />
|
||||
</div>
|
||||
<DiaryStateContext.Provider value={data}>
|
||||
<DiaryDispatchContext.Provider value={memoizedDispatches}>
|
||||
<div className="App">
|
||||
<DiaryEditor />
|
||||
<div>전체 일기 : {data.length}</div>
|
||||
<div>기분 좋은 일기 : {goodCount}</div>
|
||||
<div>기분 나쁜 일기 : {badCount}</div>
|
||||
<div>기분 좋은 일기 비율: {goodRatio} %</div>
|
||||
<DiaryList />
|
||||
</div>
|
||||
</DiaryDispatchContext.Provider>
|
||||
</DiaryStateContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -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 contentInput = useRef();
|
||||
const [state, setState] = useState({
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { useContext } from "react";
|
||||
import { DiaryDispatchContext, DiaryStateContext } from "./App";
|
||||
import DiaryItem from "./DiaryItem";
|
||||
|
||||
const DiaryList = ({ onEdit, onRemove, diaryList }) => {
|
||||
const DiaryList = () => {
|
||||
const diaryList = useContext(DiaryStateContext);
|
||||
const { onEdit, onRemove } = useContext(DiaryDispatchContext);
|
||||
return (
|
||||
<div className="DiaryList">
|
||||
<h2>일기 리스트</h2>
|
||||
|
||||
Reference in New Issue
Block a user