如何在反应中使用 axios 删除单个项目 [英] how to delete a single item using axios in react

查看:55
本文介绍了如何在反应中使用 axios 删除单个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我查看了许多文章和帖子,例如 this 但它不起作用就我而言.我只需要使用 axios 从我的应用程序中的帖子列表中删除一个项目.在 axios 文档中,它说您需要将参数传递给 delete 方法.此外,我在大多数应用程序中都使用了 id,但它们的状态中没有 id.但我无法让它工作.请查看我的完整代码.我知道我的删除方法有误,请帮我改正:

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>
        );
    }
}

我也在控制台中看到了这个错误:未捕获(承诺)类型错误:无法将未定义或空值转换为对象在 get 方法中的 Function.values 处.再次感谢.

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.

推荐答案

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

You are not specifying what your Post component should delete. In other words, the props.delete is not receiving an id to pass up to your parent component. In order to do that, you can change that to () => props.delete(props.id) and then in your parent component you need to have the handleDelete method receive the id of the item you want to target which is the id we passed up earlier from Post.

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

I don't know how your server is set up but using the axios request you originally have in your question your code would look like this:

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 语句被注释掉了).

Here's a CodeSandbox (using some dummy data in the constructor) displaying the item being passed in a console.log() (axios statement is commented out).


如何使用 Firebase REST API 发出 axios 删除请求

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

Oh sorry, I did not see that you were using Firebase. Direct REST requests are a bit different with Firebase. In your configuration the requests should look like this:

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

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

This is assuming your Firebase rules allow unauthorized requests (which I strongly advise against, seeing as anyone could send this request).

请注意,firebasePostId 是 Firebase 在您向他们发送 POST 请求时提供的推送键,实际上是 id 为您的帖子.一个例子是您在评论中提到的 -LOLok8zH3B8RonrWdZs.

Please note that firebasePostId is the push key provided by Firebase when you send POST requests to them, and are in fact a great choice of id for your posts. An example of one is -LOLok8zH3B8RonrWdZs which you mentioned in the comments.

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

For more information on Firebase REST API syntax, check out their documentation.

这篇关于如何在反应中使用 axios 删除单个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆