小龙女妈妈 發表於 2020-12-17 14:25:00

react增删改查

<p>react增删改查</p>
<pre><code class="language-js">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 =&gt; {
      this.setState({
            : e.target.value
      })
    }
    find = () =&gt; {
      axios.get("http://localhost:3001/list").then(res =&gt; {
            this.setState({
                list: res.data
            })
      })
    }
    add = () =&gt; {
      axios.post("http://localhost:3001/list", {
            username: this.state.username,
            age: this.state.age
      }).then(res =&gt; {
            this.find()
      })
    }
    del = (id) =&gt; {
      axios.delete("http://localhost:3001/list/" + id).then(res =&gt; {
            this.find()
      })
    }
    update = (item) =&gt; {
      let value =prompt("请输入修改内容..",item.username+","+item.age)
      if(value){
            var arr = value.split(",")
            //派发 patch请求
            axios.patch("http://localhost:3001/list/"+item.id,{
                username:arr,
                age:arr
            }).then(res=&gt;{
                this.find()
            })
      }
    }
    select = () =&gt; {
      axios.get("http://localhost:3001/list?username_like=" + this.state.username).then(res =&gt; {
            console.log(res)
            this.setState({
                list: res.data
            })
      })
    }
    render() {
      let { list, username, age } = this.state
      return (
            &lt;div&gt;
                &lt;label&gt;用户名:&lt;input id="username" value={username} onChange={this.handleChange} placeholder="请输入用户名"&gt;&lt;/input&gt;&lt;/label&gt;
                &lt;label&gt;年龄:&lt;input id="age" value={age} onChange={this.handleChange} placeholder="请输入年龄"&gt;&lt;/input&gt;&lt;/label&gt;
                &lt;button onClick={this.add}&gt;添加&lt;/button&gt;
                &lt;button onClick={this.select}&gt;查询&lt;/button&gt;
                &lt;ul&gt;
                  {
                        list.map((item, index) =&gt; {
                            return &lt;li key={index}&gt;{item.username}---{item.age}
                              &lt;button onClick={this.del.bind(this, item.id)}&gt;删除&lt;/button&gt;
                              &lt;button onClick={this.update.bind(this, item)}&gt;修改&lt;/button&gt;
                            &lt;/li&gt;
                        })
                  }
                &lt;/ul&gt;
            &lt;/div&gt;
      )
    }
}

</code></pre>


</div>
<div id="MySignature" role="contentinfo">
    请用今天的努力,让明天没有遗憾。<br><br>
来源:https://www.cnblogs.com/cupid10/p/14149440.html
頁: [1]
查看完整版本: react增删改查