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

bru*_*ohg 2 javascript reactjs axios

我正在从 jsonplaceholder API 获取数据到我的状态。如何使用该deleteContact()方法删除数据?我最大的挣扎是如何使deleteContact()方法正确。

这种方法有错吗?

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;
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

Dac*_*nny 5

这里有几件事要修改 - 首先,鉴于您的 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>);
}
Run Code Online (Sandbox Code Playgroud)

另外,请注意传递的“箭头函数”的使用onClick

() => this.deleteContact(user.id) 
Run Code Online (Sandbox Code Playgroud)

箭头函数提供了一种方便的方法来调用绑定到当前组件实例的类方法。这对于确保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 });
    })
}
Run Code Online (Sandbox Code Playgroud)

希望有帮助!

更新

另一个注意事项;根据文档,您的代码期望 API 在请求https://jsonplaceholder.typicode.com/后返回项目列表,DELETE这似乎不是 API 的行为。解决此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 });
    })
}
Run Code Online (Sandbox Code Playgroud)

另请注意,此占位符 API实际上并未从服务器中删除数据,这意味着删除操作似乎无效。