简体   繁体   English

使用Axios和ReactJS从API中删除数据

[英]Delete data from API with Axios and ReactJS

I am fetching data from the jsonplaceholder API into my state. 我从jsonplaceholder API获取数据到我的状态。 How can I remove the data with the deleteContact() method? 如何使用deleteContact()方法删除数据? My greatest struggle is how to get the deleteContact() method right. 我最大的困难是如何使deleteContact()方法正确。

Is this approach wrong? 这种方法有误吗?

 class RemoveFromAPI extends Component { state = { users: [] } componentDidMount() { axios.get(`https://jsonplaceholder.typicode.com/users`) .then(res => { const users = res.data; this.setState({ users }); }) } deleteContact () { axios.delete(`https://jsonplaceholder.typicode.com/users/${id}`); .then(res => { const users = res.data; this.setState({ users }); }) } render() { const {users} = this.state return ( <div> <ul> { this.state.users.map(user => <li>{user.name}</li>)} </ul> <button onClick={deleteContact} > Remove </button> </div> ); } } RemoveFromAPI.propTypes = {}; export default RemoveFromAPI; 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> 

A few things to revise here - first, it seems you need to pass the user.id to the deleteContact() function, given that your axios request requires the user id as part of the request URL. 这里要修改一些事项 - 首先,似乎你需要将user.id传递给deleteContact()函数,因为你的axios请求需要用户id作为请求URL的一部分。 This typically means moving the "Remove" button into the map() render callback so that each user id can be passed through the buttons click handler: 这通常意味着将“删除”按钮移动到map()渲染回调中,以便每个用户ID都可以通过按钮单击处理程序传递:

render() {

    const {users} = this.state

    return (<div>
            <ul>
            { 
              this.state.users.map(user => (
              <li>{user.name}
                  <button onClick={ () => this.deleteContact(user.id) } >Remove</button>
              </li>))
            }
            </ul>
        </div>);
}

Also, note the use of the "arrow function" passed on onClick : 另外,请注意使用onClick传递的“箭头函数”:

() => this.deleteContact(user.id) 

Arrow functions provide a convenient way to call a class methods that are bound to the current component instance. 箭头函数提供了一种方便的方法来调用绑定到当前组件实例的类方法。 This is important to ensure methods like setState() work as expected from inside the class method being called. 这对于确保setState()方法在调用的类方法中按预期工作非常重要。

Finally, the deleteContact() method itself needs some minor revisions. 最后, deleteContact()方法本身需要一些小的修订。 Ensure the id parameter is declared as a function argument and also remove the ; 确保将id参数声明为函数参数,并删除; following your axios.delete() to avoid a syntax error, like so: 跟随您的axios.delete()以避免语法错误,如下所示:

deleteContact (id) { // <-- declare id parameter
    axios.delete(`https://jsonplaceholder.typicode.com/users/${id}`) // <-- remove ;
    .then(res => {
        const users = res.data;
        this.setState({ users });
    })
}

Hope that helps! 希望有所帮助!

Update 更新

Another note; 另一个说明; your code is expecting the API at https://jsonplaceholder.typicode.com/ to return list of items after a DELETE request according to the documentation this doesnt seem to be the API's behavior. 您的代码期望https://jsonplaceholder.typicode.com/上的API返回DELETE请求后的项目列表,根据文档,这似乎不是API的行为。 One way to address this would be to update deleteContact() to first issue the DELETE request, followed by a GET request like so: 解决此问题的一种方法是更新deleteContact()以首先发出DELETE请求,然后发出如下的GET请求:

deleteContact (id) {

    // Issue DELETE request
    axios.delete(`https://jsonplaceholder.typicode.com/users/${id}`)
    .then(() => {

        // Issue GET request after item deleted to get updated list
        // that excludes user of id
        return axios.get(`https://jsonplaceholder.typicode.com/users`)
    })
    .then(res => {

        // Update users in state as per-usual
        const users = res.data;
        this.setState({ users });
    })
}

Note also, this placeholder API does not actually remove data from the server which will mean the delete operation will appear to have no effect. 另请注意,此占位符API 实际上并未从服务器中删除数据,这意味着删除操作似乎无效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM