해결된 질문
작성
·
402
·
수정됨
0
import { useState, useEffect, useRef, useMemo } from "react";
import "./App.css";
import DiaryEditor from "./DiaryEditor";
import DiaryList from "./DiaryList";
import OptimizeTest from "./OptimizeTest";
const App = () => {
const [data, setData] = useState([]);
const dataId = useRef(0);
const getData = async () => {
const res = await fetch(
"https://jsonplaceholder.typicode.com/comments"
).then((res) => res.json());
const initData = res.slice(0, 10).map((it) => {
return {
author: it.email,
content: it.body,
emotion: Math.floor(Math.random() * 5) + 1,
created_date: new Date().getTime(),
id: dataId.current++,
};
});
setData(initData);
console.log(initData);
};
useEffect(() => {
getData();
}, []);
const onCreate = (author, content, emotion) => {
const created_date = new Date().getTime();
const newItem = {
author,
content,
emotion,
created_date,
id: dataId.current,
};
dataId.current += 1;
setData([newItem, ...data]);
};
const onRemove = (targetId) => {
const newDiaryList = data.filter((it) => it.id !== targetId);
console.log(newDiaryList);
setData(newDiaryList);
};
const onChange = (targetId, newContent) => {
for (let i in data) {
if (data[i].id === targetId) {
data[i].content = newContent;
}
}
setData([...data]);
};
const getAnalysis = useMemo(() => {
console.log("일기 분석 시작 ");
const goodCount = data.filter((it) => it.emotion >= 3).length;
const badCount = data.length - goodCount;
const goodRatio = (goodCount / data.length) * 100;
return { goodCount, badCount, goodRatio };
}, [data.length]);
const { goodCount, badCount, goodRatio } = getAnalysis;
return (
<div className="App">
<OptimizeTest />
<DiaryEditor onCreate={onCreate} />
<div>전체 일기 : {data.length}</div>
<div>좋은 감정 점수 개수: {goodCount}</div>
<div>나쁜 감정 점수 개수: {badCount}</div>
<div>좋은 감정 점수 비율: {goodRatio}%</div>
<DiaryList onRemove={onRemove} onChange={onChange} diaryList={data} />
</div>
);
};
export default App;
답변