Table of Contents
start using
Create update and delete views
Implement update release function
实现删除帖子功能
总结
Home CMS Tutorial WordPress Updating and deleting posts in a React-based blog application: Part 4

Updating and deleting posts in a React-based blog application: Part 4

Sep 04, 2023 am 09:05 AM

In the previous part of this tutorial series, you learned how to implement the add and display post functionality. In this part of the tutorial series on creating a blog application in React, you will implement functionality to update and delete blog posts.

start using

Let's start by cloning the source code for the final part of this series.

https://github.com/royagasthyan/ReactBlogApp-AddPost
Copy after login

After cloning the directory, navigate to the project directory and install the required dependencies.

cd ReactBlogApp-AddPost
npm install
Copy after login

Start the Node.js server and the application will run at http://localhost:7777/index.html#/.

Create update and delete views

Let’s modify the list of blog posts to display the data in a table with update and delete icons. In the render method of the ShowPost component, replace the existing div with the table, as shown in the code:

<table className="table table-striped">
            <thead>
              <tr>
                <th>#</th>
                <th>Title</th>
                <th>Subject</th>
                <th></th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              {
                this.state.posts.map(function(post,index) {
                   return <tr key={index} >
                            <td>{index+1}</td>
                            <td>{post.title}</td>
                            <td>{post.subject}</td>
                            <td>
                              <span className="glyphicon glyphicon-pencil"></span>
                            </td>
                            <td>
                              <span className="glyphicon glyphicon-remove"></span>
                            </td>
                          </tr>
                }.bind(this))
              }
            </tbody>
</table>
Copy after login

As shown in the code above, you have modified the existing code to display the posts in a table format. You mapped the posts variable to iterate over the posts collection and dynamically create the required tr and td.

Save the above changes and restart the server. Point your browser to http://localhost:7777/home#/ and you should be able to see a list of blog posts in tabular format.

在基于 React 的博客应用程序中更新和删除帖子:第 4 部分

Implement update release function

To implement update publishing functionality, you need to attach a click event to the edit icon. Modify the edit icon span as shown:

<span onClick={this.updatePost.bind(this,post._id)} className="glyphicon glyphicon-pencil"></span>
Copy after login

As shown in the code above, you have passed the post ID as a parameter to the updatePost method.

Create a method updatePost inside the ShowPost component.

updatePost(id){
  hashHistory.push('/addPost/' + id);
}
Copy after login

As shown in the code above, you have triggered a redirect to the add post page using the ID of the edited item. In the add post page you will get the details of the blog post with the passed ID and populate the details.

Modify the router to include the optional id parameter in the add post page.

<Route component={AddPost} path="/addPost(/:id)"></Route>
Copy after login

Inside the AddPost component, create a method called getPostWithId to get the blog post details using the id. Within the getPostWithId method, make an AJAX call to the getPostWithId API within app.js.

getPostWithId(){
  var id = this.props.params.id;
  var self = this;
  axios.post('/getPostWithId', {
    id: id
  })
  .then(function (response) {
    if(response){
      self.setState({title:response.data.title});
      self.setState({subject:response.data.subject});  
    }
  })
  .catch(function (error) {
    console.log('error is ',error);
  });
}
Copy after login

You have updated the state variables title and subject with the response received from the getPostWithId API method.

Modify the title and subject text boxes to display the value of the status variable.

<div className="form-group">
    <input value={this.state.title} type="text" onChange={this.handleTitleChange} className="form-control" id="title" name="title" placeholder="Title" required />
</div>
               
<div className="form-group">
    <textarea value={this.state.subject} className="form-control" onChange={this.handleSubjectChange} type="textarea" id="subject" placeholder="Subject" maxlength="140" rows="7"></textarea>
</div>
Copy after login

Now, let us create the getPostWithId API in app.js to make a database call to the MongoDB database to get the post details with a specific ID. This is the getPostWithId API method:

app.post('/getPostWithId', function(req,res){
  var id = req.body.id;
  post.getPostWithId(id, function(result){
    res.send(result)
  })
})
Copy after login

In the post.js file, create a method getPostWithId to query the database for details. Its appearance is as follows:

getPostWithId: function(id, callback){
	MongoClient.connect(url, function(err, db){
		 db.collection('post').findOne({
		 	_id: new mongodb.ObjectID(id)
		 },
		 function(err, result){
			assert.equal(err, null);
	    	if(err == null){
	    		callback(result)
	    	}
	    	else{
	    		callback(false)
	    	}
		});
	})
}
Copy after login

As shown in the code above, you used the findOne API to get the details of a blog post with a specific ID.

Save the above changes and try to run the program. Click the edit icon on the home page and it will redirect to the add post page and populate the title and subject.

在基于 React 的博客应用程序中更新和删除帖子:第 4 部分

Now, to update the blog post details you need to check the idaddPost in app.js within API methods. If this is a new post, id will be undefined.

Modify the AddPost method in the AddPost component to include the id state variable.

axios.post('/addPost', {
    title: this.state.title,
    subject: this.state.subject,
    id: this.state.id
})
Copy after login

In the addPost API method, you need to check if the id parameter is undefined . If undefined, it means this is a new post, otherwise the update method needs to be called. addPost The API method is as follows:

app.post('/addpost', function (req, res) {
  var title = req.body.title;
  var subject = req.body.subject;
  var id = req.body.id;
  if(id == '' || id == undefined)
    post.addPost(title, subject ,function(result){
      res.send(result);
    }); 
  }
  else{
    post.updatePost(id, title, subject ,function(result){
      res.send(result);
    }); 
  }
})
Copy after login

In the post.js file, create a method named updatePost to update the blog post details. You will utilize the updateOne API to update the details of a blog post with a specific id. Here's what the updatePost method looks like:

updatePost: function(id, title, subject, callback){
	MongoClient.connect(url, function(err, db) {
	  	db.collection('post').updateOne( 
	  		{ "_id": new mongodb.ObjectID(id) },
	  		{ $set: 
	  			{ "title" : title,
	  			  "subject" : subject 
	  			}
	  		},function(err, result){
			assert.equal(err, null);
	    	if(err == null){
	    		callback(true)
	    	}
	    	else{
	    		callback(false)
	    	}
		});
	});
}
Copy after login

保存以上更改并重新启动服务器。登录应用程序并点击编辑图标。修改现有值并单击按钮更新详细信息。

实现删除帖子功能

要实现删除帖子功能,您需要将点击事件附加到删除图标。修改删除图标跨度如图:

<span onClick={this.deletePost.bind(this,post._id)} className="glyphicon glyphicon-remove"></span>
Copy after login

如上面的代码所示,您已将帖子 ID 作为参数传递给 deletePost 方法。

ShowPost 组件中创建一个名为 deletePost 的方法。

deletePost(id){
      
}
Copy after login

ShowPost组件构造函数中绑定该方法。

this.deletePost = this.deletePost.bind(this);
Copy after login

要在 map 函数回调中使用 this,您需要将 this 绑定到 map 函数。修改map函数回调如图:


      {
        this.state.posts.map(function(post,index) {
           return 
                    {index+1}
                    {post.title}
                    {post.subject}
                    
                      <span onClick={this.updatePost.bind(this,post._id)} className="glyphicon glyphicon-pencil"></span>
                    
                    
                      <span onClick={this.deletePost.bind(this,post._id)} className="glyphicon glyphicon-remove"></span>
                    
                  
        }.bind(this))
      }
 
Copy after login

deletePost 方法中,在调用删除 API 之前添加确认提示。

deletePost(id){
  if(confirm('Are you sure ?')){
    // Delete Post API call will be here !!
  }
}
Copy after login

现在让我们在 app.js 文件中添加 deletePost API。 API 将从 AJAX 调用中读取帖子 ID 并从 MongoDB 中删除该条目。以下是 deletePost API 的外观:

app.post('/deletePost', function(req,res){
  var id = req.body.id;
  post.deletePost(id, function(result){
    res.send(result)
  })
})
Copy after login

如上面的代码所示,您将调用 post.js 文件中的 deletePost 方法并返回结果。让我们在 post.js 文件中创建 deletePost 方法。

deletePost: function(id, callback){

	MongoClient.connect(url, function(err, db){
		 db.collection('post').deleteOne({
		 	_id: new mongodb.ObjectID(id)
		 },
		 function(err, result){
			assert.equal(err, null);
	    	console.log("Deleted the post.");
	    	if(err == null){
	    		callback(true)
	    	}
	    	else{
	    		callback(false)
	    	}
		});
	})
}
Copy after login

如上面的代码所示,post.js 文件中的 deletePost 方法将使用 MongoClient 连接到MongoDB 中的博客数据库。使用从 AJAX 调用传递的 Id ,它将从数据库中删除该帖子。

更新 home.jsx 文件中 deletePost 方法内的代码,以包含对 deletePost API 的 AJAX 调用 app.js 文件。

deletePost(id){
  if(confirm('Are you sure ?')){
    var self = this;
    axios.post('/deletePost', {
      id: id
    })
    .then(function (response) {
      
    })
    .catch(function (error) {
      
    });
  }
}
Copy after login

删除博客文章后,您需要刷新博客文章列表以反映这一点。因此,创建一个名为 getPost 的新方法,并将 componentDidMount 代码移到该函数内。这是 getPost 方法:

getPost(){
  var self = this;
  axios.post('/getPost', {
  })
  .then(function (response) {
    console.log('res is ',response);
    self.setState({posts:response.data})
  })
  .catch(function (error) {
    console.log('error is ',error);
  });
}
Copy after login

修改componentDidMount代码,如图:

componentDidMount(){
  this.getPost();

  document.getElementById('homeHyperlink').className = "active";
  document.getElementById('addHyperLink').className = "";
}
Copy after login

deletePost AJAX 调用成功回调内,调用 getPost 方法来更新博客文章列表。

deletePost(id){
  if(confirm('Are you sure ?')){
    var self = this;
    axios.post('/deletePost', {
      id: id
    })
    .then(function (response) {
      self.getPost();
    })
    .catch(function (error) {
      console.log('Error is ',error);
    });
  }
}
Copy after login

保存以上更改并重新启动服务器。尝试添加新的博客文章,然后从网格列表中单击“删除”。系统将提示您一条删除确认消息。单击确定按钮后,该条目将被删除,并且博客文章列表将被更新。

在基于 React 的博客应用程序中更新和删除帖子:第 4 部分

总结

在本教程中,您了解了如何在 React 博客应用程序中实现删除和更新博客文章功能。在本教程系列的下一部分中,您将了解如何为登录用户实现个人资料页面。

请在下面的评论中告诉我们您的想法和建议。本教程的源代码可在 GitHub 上获取。

The above is the detailed content of Updating and deleting posts in a React-based blog application: Part 4. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is WordPress easy for beginners? Is WordPress easy for beginners? Apr 03, 2025 am 12:02 AM

WordPress is easy for beginners to get started. 1. After logging into the background, the user interface is intuitive and the simple dashboard provides all the necessary function links. 2. Basic operations include creating and editing content. The WYSIWYG editor simplifies content creation. 3. Beginners can expand website functions through plug-ins and themes, and the learning curve exists but can be mastered through practice.

How To Begin A WordPress Blog: A Step-By-Step Guide For Beginners How To Begin A WordPress Blog: A Step-By-Step Guide For Beginners Apr 17, 2025 am 08:25 AM

Blogs are the ideal platform for people to express their opinions, opinions and opinions online. Many newbies are eager to build their own website but are hesitant to worry about technical barriers or cost issues. However, as the platform continues to evolve to meet the capabilities and needs of beginners, it is now starting to become easier than ever. This article will guide you step by step how to build a WordPress blog, from theme selection to using plugins to improve security and performance, helping you create your own website easily. Choose a blog topic and direction Before purchasing a domain name or registering a host, it is best to identify the topics you plan to cover. Personal websites can revolve around travel, cooking, product reviews, music or any hobby that sparks your interests. Focusing on areas you are truly interested in can encourage continuous writing

How to display child categories on archive page of parent categories How to display child categories on archive page of parent categories Apr 19, 2025 pm 11:54 PM

Do you want to know how to display child categories on the parent category archive page? When you customize a classification archive page, you may need to do this to make it more useful to your visitors. In this article, we will show you how to easily display child categories on the parent category archive page. Why do subcategories appear on parent category archive page? By displaying all child categories on the parent category archive page, you can make them less generic and more useful to visitors. For example, if you run a WordPress blog about books and have a taxonomy called "Theme", you can add sub-taxonomy such as "novel", "non-fiction" so that your readers can

How to get logged in user information in WordPress for personalized results How to get logged in user information in WordPress for personalized results Apr 19, 2025 pm 11:57 PM

Recently, we showed you how to create a personalized experience for users by allowing users to save their favorite posts in a personalized library. You can take personalized results to another level by using their names in some places (i.e., welcome screens). Fortunately, WordPress makes it very easy to get information about logged in users. In this article, we will show you how to retrieve information related to the currently logged in user. We will use the get_currentuserinfo();  function. This can be used anywhere in the theme (header, footer, sidebar, page template, etc.). In order for it to work, the user must be logged in. So we need to use

What is the WordPress good for? What is the WordPress good for? Apr 07, 2025 am 12:06 AM

WordPressisgoodforvirtuallyanywebprojectduetoitsversatilityasaCMS.Itexcelsin:1)user-friendliness,allowingeasywebsitesetup;2)flexibilityandcustomizationwithnumerousthemesandplugins;3)SEOoptimization;and4)strongcommunitysupport,thoughusersmustmanageper

How to sort posts by post expiration date in WordPress How to sort posts by post expiration date in WordPress Apr 19, 2025 pm 11:48 PM

In the past, we have shared how to use the PostExpirator plugin to expire posts in WordPress. Well, when creating the activity list website, we found this plugin to be very useful. We can easily delete expired activity lists. Secondly, thanks to this plugin, it is also very easy to sort posts by post expiration date. In this article, we will show you how to sort posts by post expiration date in WordPress. Updated code to reflect changes in the plugin to change the custom field name. Thanks Tajim for letting us know in the comments. In our specific project, we use events as custom post types. Now

How to display query count and page loading time in WordPress How to display query count and page loading time in WordPress Apr 19, 2025 pm 11:51 PM

One of our users asked other websites how to display the number of queries and page loading time in the footer. You often see this in the footer of your website, and it may display something like: "64 queries in 1.248 seconds". In this article, we will show you how to display the number of queries and page loading time in WordPress. Just paste the following code anywhere you like in the theme file (e.g. footer.php). queriesin

Can I learn WordPress in 3 days? Can I learn WordPress in 3 days? Apr 09, 2025 am 12:16 AM

Can learn WordPress within three days. 1. Master basic knowledge, such as themes, plug-ins, etc. 2. Understand the core functions, including installation and working principles. 3. Learn basic and advanced usage through examples. 4. Understand debugging techniques and performance optimization suggestions.

See all articles