react增刪改查
import React, { Component } from 'react'
import axios from 'axios'
export default class List extends Component {
constructor() {
super()
this.state = {
list: [],
username: "",
age: ""
}
}
componentDidMount() {
this.find()
}
handleChange = e => {
this.setState({
[e.target.id]: e.target.value
})
}
find = () => {
axios.get("http://localhost:3001/list").then(res => {
this.setState({
list: res.data
})
})
}
add = () => {
axios.post("http://localhost:3001/list", {
username: this.state.username,
age: this.state.age
}).then(res => {
this.find()
})
}
del = (id) => {
axios.delete("http://localhost:3001/list/" + id).then(res => {
this.find()
})
}
update = (item) => {
let value = prompt("請輸入修改內容..",item.username+","+item.age)
if(value){
var arr = value.split(",")
//派發 patch請求
axios.patch("http://localhost:3001/list/"+item.id,{
username:arr[0],
age:arr[1]
}).then(res=>{
this.find()
})
}
}
select = () => {
axios.get("http://localhost:3001/list?username_like=" + this.state.username).then(res => {
console.log(res)
this.setState({
list: res.data
})
})
}
render() {
let { list, username, age } = this.state
return (
<div>
<label>用戶名:<input id="username" value={username} onChange={this.handleChange} placeholder="請輸入用戶名"></input></label>
<label>年齡:<input id="age" value={age} onChange={this.handleChange} placeholder="請輸入年齡"></input></label>
<button onClick={this.add}>添加</button>
<button onClick={this.select}>查詢</button>
<ul>
{
list.map((item, index) => {
return <li key={index}>{item.username}---{item.age}
<button onClick={this.del.bind(this, item.id)}>刪除</button>
<button onClick={this.update.bind(this, item)}>修改</button>
</li>
})
}
</ul>
</div>
)
}
}
