TAB 2022 2학기 학회활동 [팀 스터디]
TIL 포스팅입니다.
작성자 : 40기_박지민
ref. 생활코딩 [React]
수정 (업데이트) 기능
▶ 원시 데이터 타입
string, number, boolean, bigint, undefined, symbol, null
▶ 범 객체
object, array
▶ 객체 값의 수정
newValue = {...value} → value값 복제한 새로운 데이터가 newValue의 값이 됨.
newValue 변경 후 setValue(newValue) → 컴포넌트 재실행
* 배열의 경우 {...value} 대신 [...value] 사용
▶ 수정 시의 주의점
오리지널 데이터 변경 시 기존 데이터와 변경된 데이터가 같을 경우 컴포넌트는 다시 랜더링되지 않는다.
const[value,setValue] = useState(1); setValue(2); | 랜더링 작동 |
const[value,setValue] = useState([1]); value.push(2); setValue(value); |
랜더링 미작동 (데이터 동일) |
const[value,setValue] = useState([1]); newValue = [...value] newValue.push(2); setValue(newValue); |
랜더링 작동 |
▶ 업데이트 주의점
1. 수정 시 기존의 값이 value값으로 주입되었을 때는 props에서 state로 갈아탈 것
2. 값이 변경될 때마다 변경된 값을 state로 바꿔서 그 값을 다시 피드백 받을 것
Ex)
contextControl = <li><a href={'/update/'+id} onClick={event=>{
event.preventDefault();
setMode('UPDATE');
}}>Update</a></li>
- 업데이트 버튼 구현 및 모드 추가
- contextControl을 사용한 이유는 특정 상황에서 나오게 하기 위함
function Update(props){
const [title, setTitle] = useState(props.title);
const [body, setBody] = useState(props.body);
return <article>
<h2>Update</h2>
<form onSubmit={event=>{
event.preventDefault();
const title = event.target.title.value;
const body = event.target.body.value;
props.onUpdate(title, body);
}}>
<p><input type="text" name="title" placeholder="title" value={title} onChange={event=>{
setTitle(event.target.value);
}}/></p>
<p><textarea name="body" placeholder="body" value={body} onChange={event=>{
setBody(event.target.value);
}}></textarea></p>
<p><input type="submit" value="Update"></input></p>
</form>
</article>
}
- onChange={}를 통해 값이 변경될 때마다 타이틀과 바디 값이 새로 지정된다
- 제출 버튼 클릭 시 onSubmit = {}가 호출되어 새로 지정된 타이틀과 바디 값이 각 변수에 저장된다
- useState(' ')의 0번째 원소는 상태 값을 읽는 데 사용되는 데이터, 1번째 원소는 상태 값 변경시 사용되는 함수.
if(mode === 'UPDATE'){
let title, body = null;
for(let i=0; i<topics.length; i++){
if(topics[i].id === id){
title = topics[i].title;
body = topics[i].body;
}
}
content = <Update title={title} body={body} onUpdate={(title, body)=>{
console.log(title, body);
const newTopics = [...topics]
const updatedTopic = {id:id, title:title, body:body}
for(let i=0; i<newTopics.length; i++){
if(newTopics[i].id === id){
newTopics[i] = updatedTopic;
break;
}
}
setTopics(newTopics);
setMode('READ');
}}></Update>
}
- onUpdate을 통해 수정된 값 변경 : [...topics]로 복제 데이터 newTopics에 저장. newTopics의 데이터 updatedTopic에 하나씩 분할.
- setTopics(newTopics) -> 컴포넌트 재실행
- 수정 완료 후 읽기 모드로 변경(setMode)
삭제 기능
<li><input type="button" value = "Delete" onClick={()=> {
const newTopics = []
for(let i=0; i<topics.length;i++){
if(topics[i].id !== id{
newTopics.push(topics[i]);
}
}
setTopics(newTopics);
setMode('WELCOME');
}} /><li>
- event.preventDefault(); 불필요
- newTopics 빈 배열 생성. topics와는 다른 데이터이기 때문에 newtopics에 push하여 새로운 topics 생성
* topics의 id가 현재 선택된 id와 다를 경우 id값이 일치하지 않는 topic들만 push
- setTopics(newTopics) -> 컴포넌트 재실행
- 수정 완료 후 상세보기 모드(WELCOME)로 변경(setMode)
'22 - 1학기 > 팀 스터디' 카테고리의 다른 글
[웹 FE 스터디] THE BASICS OF REACT ~ 3.5 Inputs and State (0) | 2022.09.29 |
---|---|
[React] Vanila JS vs React Js | JSX (1) | 2022.09.29 |
[웹 FE 스터디] React : Creat~Delete (0) | 2022.09.27 |
[웹 FE 스터디] 리액트 시작하기(2) - JSX, elements, props (0) | 2022.09.22 |
[웹 FE 스터디] JSX, Rendering Elements, Components, Props (0) | 2022.09.22 |