인프런, 유데미/한입 크기로 잘라 먹는 리액트
데이터 추가하기
5_hyun
2022. 5. 24. 23:16
반응형
App
DiaryEditor DiaryList
리엑트는 이런 트리 구조로 이루어져 있다.
0번 레벨: App
1번 레벨: DiaryEditor, DiaryList
이렇게 있고 같은 레벨끼리는 데이터를 주고 받을 수 없다.
React는 단방향으로 데이터가 흐른다, 즉 위에서 아래로만 흐른다.
이벤트가 발생하면 위로 올라가는 흐름이 나오고 데이터를 추가하면 아래로 내려가는 흐름이 나온다.
-App.js
import { useRef, useState } from "react";
import "./App.css";
import DiaryEditor from "./DiaryEditor";
import DiaryList from "./DiaryList";
const App = () => {
const [data, setData] = useState([]);
const dataId = useRef(0);
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]);
};
return (
<div className="App">
<DiaryEditor onCreate={onCreate} />
<DiaryList diaryList={data} />
</div>
);
};
export default App;
const [data, setData]에 글을 저장한다. 그리고 Id는 useRef를 통해 만들어주고 한 글이 만들어지면 1을 추가해 다음 글에서는 1 높은 Id를 갖도록한다.
-DiaryEditor.js
const handleSubmit = () => {
if (state.author.length < 1) {
authorInput.current.focus();
return;
}
if (state.content.length < 5) {
contentInput.current.focus();
return;
}
onCreate(state.author, state.content, state.emotion);
alert("저장 성공!");
setState({
author: "",
content: "",
emotion: 1,
});
};
DiaryEditor.js의 handleSubmit 함수 안에 onCreate가 호출되고 App.js의 onCreate로 데이터를 전달해주고 data 리스트에 글이 업데이트되어 저장된다.
반응형