일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 리터럴 타입
- TS
- tailwind
- ESlint
- app router
- 태그된 유니온
- map
- CORS
- 공변성
- async/await
- dfs
- RTK Query
- 투포인터
- useAppDispatch
- Jest
- recoil
- 호이스팅
- SSR
- Cypress
- Promise
- 무한 스크롤
- React
- 반공변성
- 타입 좁히기
- 결정 알고리즘
- autosize
- 인터섹션
- CI/CD
- webpack
- 이분 검색
Archives
- Today
- Total
짧은코딩
데이터 추가하기 본문
반응형
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 리스트에 글이 업데이트되어 저장된다.
반응형
'인프런, 유데미 > 한입 크기로 잘라 먹는 리액트' 카테고리의 다른 글
데이터 수정하기 (0) | 2022.05.25 |
---|---|
데이터 삭제하기 (0) | 2022.05.25 |
리스트 렌더링 (0) | 2022.05.24 |
간단한 일기장 프로젝트-State로 사용자 입력처리, useRef (2) | 2022.05.23 |
React 기초-State, Props (0) | 2022.05.22 |
Comments