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

Javascript 使用Axios和ReactJS从API中删除数据,javascript,reactjs,axios,Javascript,Reactjs,Axios,我正在将数据从jsonplaceholder API提取到我的状态。如何使用deleteContact()方法删除数据?我最大的困难是如何正确使用deleteContact()方法 这种方法错了吗 类RemoveFromAPI扩展组件{ 状态={ 用户:[] } componentDidMount(){ axios.get(`https://jsonplaceholder.typicode.com/users`) 。然后(res=>{ const users=res.data; this.se

我正在将数据从jsonplaceholder API提取到我的状态。如何使用
deleteContact()
方法删除数据?我最大的困难是如何正确使用
deleteContact()
方法

这种方法错了吗

类RemoveFromAPI扩展组件{
状态={
用户:[]
}
componentDidMount(){
axios.get(`https://jsonplaceholder.typicode.com/users`)
。然后(res=>{
const users=res.data;
this.setState({users});
})
}
删除联系人(){
axios.delete(`https://jsonplaceholder.typicode.com/users/${id}`);
。然后(res=>{
const users=res.data;
this.setState({users});
})
}
render(){
const{users}=this.state
返回(
    {this.state.users.map(user=>
  • {user.name}
  • )}
去除 ); } } RemoveFromAPI.propTypes={}; 导出默认RemoveFromAPI
这里有几点需要修改-首先,鉴于axios请求需要将用户id作为请求URL的一部分,您似乎需要将
user.id
传递给
deleteContact()
函数。这通常意味着将“删除”按钮移动到
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>);
}
箭头函数提供了一种方便的方法来调用绑定到当前组件实例的类方法。这对于确保像
setState()
这样的方法从被调用的类方法内部按预期工作是很重要的

最后,
deleteContact()
方法本身需要一些小的修改。确保
id
参数声明为函数参数,并删除
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 });
    })
}

另外请注意,此占位符API意味着删除操作似乎没有效果。

欢迎使用堆栈溢出。您的意思是要将用户从状态中删除吗?谢谢!获取此错误:TypeError:this.state.users.map不是一个函数不欢迎:)您是立即看到此错误,还是在单击“删除”按钮后看到此错误?从文档中单击“删除”按钮后,似乎
删除(
{id}
不会返回用户列表(如代码所期望的那样)-一个选项是发出“删除”请求,然后执行“列表查询”。你想让我更新代码来显示这个吗?是的,那太好了!
deleteContact (id) { // <-- declare id parameter
    axios.delete(`https://jsonplaceholder.typicode.com/users/${id}`) // <-- remove ;
    .then(res => {
        const users = res.data;
        this.setState({ users });
    })
}
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 });
    })
}