首页 > 解决方案 > how to delete a single item using axios in react

问题描述

I have looked into many articles and posts like this but it does not work in my case.I simply need to delete an item from my post list in my application using axios. In the axios docs it says you need to pass in the params to the delete method. Also I have sen in most apps they use ids without having ids in their state. But i cannot get it working. Please see my entire code. I know that my delete method is wrong please help me fix it:

    // The individual post component
    const Post = props => (
    <article className="post">
        <h2 className="post-title">{props.title}</h2>
        <hr />
        <p className="post-content">{props.content}</p>
        <button onClick={props.delete}>Delete this post</button>
    </article>
);

// The seperate form component to be written later

class Form extends React.Component {}

// The posts loop component

class Posts extends React.Component {
    state = {
        posts: [],
        post: {
            title: "",
            content: ""
        }
        // error:false
    };

    componentDidMount() {
        const { posts } = this.state;
        axios
            .get("url")
            .then(response => {
            const data = Object.values(response.data);
            this.setState({ posts : data });
            });
    }
    handleChange = event => {
        const [name , value] = [event.target.name, event.target.value];
        // const value = event.target.value;
        const { post } = this.state;
        const newPost = {
            ...post,
            [name]: value
        };
        this.setState({ post: newPost });
    };

    handleSubmit = event => {
        event.preventDefault();
        const {post} = this.state;
        const {posts} = this.state;
        axios
            .post("url", post)
            .then(response => {
            // console.log(response);
            const newPost = Object.values(response.data);
            this.setState({ post: newPost });
            const updatedPosts =  [...posts, {title:post.title,content:post.content}];
            this.setState({ posts: updatedPosts});
            // console.log(post);
            console.log(updatedPosts);
            console.log(this.state.posts);
            });
    };

    handleDelete = () => {
        const { post } = this.state;
        axios.delete("url",{params: {id: post.id}})
        .then(response => {
            console.log(response);
        });
    };

    render() {
        let posts = <p>No posts yet</p>;
        if (this.state.posts !== null) {
            posts = this.state.posts.map(post => {
                return <Post 
                                 key={post.id} 
                                 {...post}
                                 delete={this.handleDelete}/>;
            });
        }

        return (
            <React.Fragment>
                {posts}
                <form className="new-post-form" onSubmit={this.handleSubmit}>
                    <label>
                        Post title
                        <input
                            className="title-input"
                            type="text"
                            name="title"
                            onChange={this.handleChange}
                        />
                    </label>
                    <label>
                        Post content
                        <input
                            className="content-input"
                            type="text"
                            name="content"
                            onChange={this.handleChange}
                        />
                    </label>
                    <input className="submit-button" type="submit" value="submit" />
                </form>
            </React.Fragment>
        );
    }
}

I also see this Error in console: Uncaught (in promise) TypeError: Cannot convert undefined or null to object at Function.values which is in get method. Thanks again.

标签: reactjsfirebaseaxios

解决方案


您没有指定您的Post组件应该删除什么。换句话说,props.delete没有接收id到传递给您的父组件。为了做到这一点,您可以将其更改为() => props.delete(props.id),然后在您的父组件中,您需要让handleDelete方法接收id您想要定位的项目,这是id我们之前从Post.

我不知道您的服务器是如何设置的,但是使用您最初在问题中提出的 axios 请求,您的代码将如下所示:

handleDelete = (itemId) => {
    // Whatever you want to do with that item
    axios.delete("url", { params: { id: itemId } }).then(response => {
      console.log(response);
    });

这是一个CodeSandbox(在构造函数中使用一些虚拟数据),显示正在传递的项目console.log()(axios 语句被注释掉)。


编辑:如何使用 Firebase REST API 使 axios 删除请求

哦,抱歉,我没有看到您使用的是 Firebase。直接 REST 请求与 Firebase 略有不同。在您的配置中,请求应如下所示:

axios.delete(`${url}/${firebasePostId}.json`).then(response => {
    console.log(response)
})

这是假设您的 Firebase 规则允许未经授权的请求(我强烈建议不要这样做,因为任何人都可以发送此请求)。

请注意,这firebasePostId是 Firebase 在您向POST他们发送请求时提供的推送键,实际上是id您发布帖子的绝佳选择。-LOLok8zH3B8RonrWdZs您在评论中提到的一个示例。

有关 Firebase REST API 语法的更多信息,请查看他们的文档


推荐阅读