sm 기술 블로그
9강. Delete 본문
DELETE는 크게 어렵지 않다.
DELETE의 최종 코드를 한번 보자.
... 생략 ...
function App() {
... 생략 ...
else if (mode === 'READ'){
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 = <Article title={title} body={body}></Article>;
contextControll = <>
<li><a href={"/update/" + id} onClick={event=>{
event.preventDefault();
setMode("UPDATE");
}}>Update</a></li>
<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>
</>;
}
... 생략 ...
return (
... 생략 ...
<ul>
<li><a href="/create" onClick={event => {
event.preventDefault();
setMode('CREATE');
}}>Create</a></li>
{contextControll}
</ul>
</div>
);
}
export default App;
실제로 추가된 부분은
contextControll = <>
... 생략 ...
<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>
</>;
이 코드이 이다.
먼저 리액트는 태그를 다룰때 하나의 태그 안에 있어야한다.
하지만 이미 <li> 태그 update를 다루는 부분이 있기 때문에 태그를 하나 더 사용해야 한다.
이때 <></>로 빈태그 를 넣어주면 하나의 태그로 묶을 수 있다.
삭제는 간단히 기존 배열에서 해당 아이디만 제거하고 새로운 배열에 추가한 후 setTopics를 진행하면 된다.
https://github.com/denist2322/youtube_react/commit/1c8c5d1690d7896693784a16d94376b0e3473c7d
'리액트' 카테고리의 다른 글
비밀번호 보기/ 숨기기 기능 - 코드 (0) | 2022.09.04 |
---|---|
ReactRouter (여러 주소를 사용하기 위한 라이브러리) (0) | 2022.09.01 |
8강. Update (0) | 2022.08.31 |
7강. Create (0) | 2022.08.31 |
6강. state (0) | 2022.08.31 |
Comments