当前位置: 首页 > 面试题库 >

如何在React中使用axios删除单个项目

武博艺
2023-03-14
问题内容

我已经研究了许多类似这样的文章和帖子,但在我的情况下不起作用,我只需要使用axios从我的应用程序中的帖子列表中删除一个项目即可。在axios文档中,它说您需要将参数传递给delete方法。另外,在大多数应用中,我都使用过ID,而ID却没有处于状态。但是我不能让它工作。请查看我的整个代码。我知道我的删除方法是错误的,请帮助我修复它:

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

我还在控制台中看到此错误:未捕获(承诺)TypeError:无法将未定义或null转换为get方法中Function.values的对象。再次感谢。


问题答案:

您没有指定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语法的更多信息,请查看其文档。



 类似资料:
  • 问题内容: 这是我认为的相关代码: 单击复选框后,我希望从数据库中删除数组中的适当对象。 我的功能如下: 但是,这将删除数据库中的所有条目。我希望它仅删除有问题的特定对象。反正我有这样做吗? 问题答案: 好,知道了。 循环使用时,请使用。这使您可以将参数作为参数发送到函数,并且效果很好。

  • 问题内容: 当我卷曲东西时,它可以正常工作: 我如何使它与axios一起正常工作?如果这很重要,我正在使用react: 由于某些原因,这不起作用。 问题答案: 这是我如何使用axios在react中上传文件 资源

  • 问题内容: 我想轻松删除多个表,而无需在删除查询中实际列出表名,并且要删除的表的前缀为“ wp_” 问题答案: 只需分享其中一种解决方案: mysql> SELECT CONCAT(“ DROP TABLE”, GROUP_CONCAT(TABLE_NAME))as stmt 从information_schema.TABLES WHERE TABLE_SCHEMA =“ your_db_name

  • 我想在android studio中删除一个项目,所有文件都应该从目录中删除。 但我需要一个更好的解决方案,以删除它永久在目录中,也与安全模式。 以上所述的最佳解决方案是哪一种,或者是否有任何解决方案?希望能得到解决。谢谢!

  • 我正在使用mongodb atlas,我已经建立了一个值。以下是用户收集的示例文档详细信息。 我试图显示除一个文档外的所有文档。 我已经显示了除测试之外的所有值_id:ObjectId(“5f7f193585d5f70c177f6d27”)在项目集合中。但我不能。 你能帮我解决这个问题吗。提前谢谢。

  • 我用编写的代码: 我的: 和错误: 未捕获(promise中)错误:在xmlHttpRequest.HandleError(xhr.js:87)的createError(createError.js:16)处出现网络错误 谁来帮帮我?