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

编程入门 行业动态 更新时间:2024-10-10 08:24:35
本文介绍了如何在React中使用axios删除单个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我看过很多文章和帖子,例如此,但它不起作用我只需要使用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> ); } }

我还在控制台中看到此错误: 未捕获(承诺)TypeError:无法将未定义或null转换为对象 在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,这是我们向上传递的id早于Post.

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.直接REST请求与Firebase有所不同.在您的配置中,请求应如下所示:

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.

更多推荐

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

本文发布于:2023-11-28 04:47:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1641010.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:项目   如何在   React   axios

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!