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

王林
王林Original
2023-09-04 09:05:011316browse

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

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

cd ReactBlogApp-AddPost
npm install

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>

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>

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

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>

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

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>

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

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

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

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

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

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

实现删除帖子功能

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

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

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

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

deletePost(id){
      
}

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

this.deletePost = this.deletePost.bind(this);

要在 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))
      }
 

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

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

现在让我们在 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)
  })
})

如上面的代码所示,您将调用 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)
	    	}
		});
	})
}

如上面的代码所示,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) {
      
    });
  }
}

删除博客文章后,您需要刷新博客文章列表以反映这一点。因此,创建一个名为 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);
  });
}

修改componentDidMount代码,如图:

componentDidMount(){
  this.getPost();

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

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

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

在基于 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:
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