2swan
React 추가, 삭제(Mybatis) 본문
App.js
import BoardForm from './BoardForm';
import BoardList from './BoardList';
import {useEffect} from "react"
import axios from "axios"
import {useState} from "react"
import './App.css';
function App() {
const [listContent, setListContent] = useState([])
useEffect(()=>{
listBoard()
},[])
//추가(Form.js 입력2 방법)
const insertBoard = (data)=>{ //data는 추가된 내용
console.log(data)
axios.post('insert',{
title: data.title,
content: data.content
}).then((resp)=>{
console.log('resp : ', resp)
alert("등록완료")
setListContent(listContent.concat(
{
num : resp.data.num,
title: data.title,
content: data.content,
...listContent
}
))
})
}
//전체보기
const listBoard = ()=>{
axios.get("list").then((resp)=>{
console.log(resp.data);
setListContent(resp.data)
})
}
//삭제
const deleteBoard = (num)=>{
axios.delete("delete/"+num)
.then(()=>{
alert("삭제 성공")
setListContent(listContent.filter(board=>board.num !== num))
})
}
return (
<div style={{padding:'20px'}}>
<h1>app08_SimpleBoard_insertBoard</h1>
<hr/>
<BoardForm listBoard={listBoard}
insertBoard={insertBoard}/>
<hr/>
<BoardList lists={listContent} deleteBoard={deleteBoard}/>
</div>
);
}
export default App;
BoardForm.js
import {useState} from "react"
import axios from "axios"
const BoardForm = ({listBoard, insertBoard})=> {
const [formContent, setFormContent] = useState({
title: '',
content: ''
})
const getValue = (e)=>{
setFormContent({
...formContent,
[e.target.name] : e.target.value
})
}
//추가
const submitBoard = ()=>{
axios.post('insert',{
title: formContent.title,
content: formContent.content
}).then(()=>{
alert("등록완료")
listBoard();
})
}
return(
<div>
<input type="text" name="title" placeholder="제목" value={formContent.title}
onChange={getValue}/><br/><br/>
<textarea name="content" rows="10" cols={40} value={formContent.content}
onChange={getValue}/><br/>
<button onClick={submitBoard}>입력</button>
<button onClick={()=>insertBoard(formContent)}>입력2</button>
</div>
)
}
export default BoardForm;
BoardItem.js
const BoardItem = ({board, deleteBoard})=>{
return(
<div>
<h1>BoardItem</h1>
번호: {board.num}<br/>
제목: {board.title}<br/>
내용: {board.content}<br/>
<button onClick={()=>deleteBoard(board.num)}>삭제</button>
</div>
)
}
export default BoardItem;
BoardList.js
import BoardItem from "./BoardItem";
const BoardList=({lists, deleteBoard})=>{
return(
<div>
{
lists.map((board)=>(
<BoardItem key={board.num}
board = {board}
deleteBoard = {deleteBoard}/>
))
}
</div>
)
}
export default BoardList;
'Programming > React' 카테고리의 다른 글
React Router 예제(Class 방식) (0) | 2023.09.12 |
---|---|
React DB 연결(Mybatis) (0) | 2023.09.11 |
React DB 연결(JPA) (0) | 2023.09.11 |
React 추가, 삭제(JPA) (0) | 2023.09.11 |
React Practice(3) (0) | 2023.09.06 |