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

在本教程系列的前一部分中,您了解了如何實現添加和顯示帖子功能。在有關在 react 中創建博客應用程序的教程系列的這一部分中,您將實現更新和刪除博客文章的功能。

開始使用

讓我們開始克隆本系列最后一部分的源代碼。

https://github.com/royagasthyan/ReactBlogApp-AddPost 

克隆目錄后,導航到項目目錄并安裝所需的依賴項。

cd ReactBlogApp-AddPost npm install 

啟動 Node.JS 服務器,應用程序將在 http://localhost:7777/index.html#/ 上運行。

創建更新和刪除視圖

讓我們修改博客文章列表,以帶有更新和刪除圖標的表格形式顯示數據。在 ShowPost 組件的 render 方法中,將現有的 div 替換為表格,如代碼所示:


{ this.state.posts.map(function(post,index) { return

}.bind(this)) }

# Title Subject
{index+1} {post.title} {post.subject}

如上面的代碼所示,您已修改現有代碼以以表格形式顯示帖子。您已映射 posts 變量以迭代 posts 集合并動態創建所需的 trtd

保存以上更改并重新啟動服務器。將瀏覽器指向 http://localhost:7777/home#/,您應該能夠以表格格式查看博客文章列表。

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

實現更新發布功能

要實現更新發布功能,您需要將單擊事件附加到編輯圖標。修改編輯圖標span如圖:?

<span onclick="{this.updatePost.bind(this,post._id)}" classname="glyphicon glyphicon-pencil"></span> 

如上面的代碼所示,您已將帖子 ID 作為參數傳遞給 updatePost 方法。

在 ShowPost 組件內創建一個方法 updatePost 。

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

如上面的代碼所示,您已使用已編輯項目的 ID 觸發了到添加帖子頁面的重定向。在添加帖子頁面中,您將獲得帶有傳遞的 ID 的博客帖子的詳細信息并填充詳細信息。

修改路由器以在添加帖子頁面中包含可選的 id 參數。

<route component="{AddPost}" path="/addPost(/:id)"></route>

在 AddPost 組件內,創建一個名為 getPostWithId 的方法,以使用 id 獲取博客文章的詳細信息。在 getPostWithId 方法內,對 app.js 內的 getPostWithId API 進行 ajax 調用。

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

通過從 getPostWithId API 方法收到的響應,您已更新狀態變量 title 和 subject。

修改 title 和 subject 文本框以顯示狀態變量的值。

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

現在,讓我們在 app.js 中創建 getPostWithId API,以對 mongodb 數據庫進行數據庫調用,以獲取具有特定 ID 的帖子詳細信息。這是 getPostWithId API 方法:

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

在 post.js 文件中,創建一個方法 getPostWithId 來查詢數據庫以獲取詳細信息。其外觀如下:

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

如上面的代碼所示,您使用了 findOne API 來獲取具有特定 ID 的博客文章的詳細信息。

保存以上更改并嘗試運行程序。單擊主頁上的編輯圖標,它將重定向到添加帖子頁面并填充標題和主題。

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

現在,要更新博客文章詳細信息,您需要檢查 id在 app.js 中的 addPost API 方法內。如果是新帖子,則 id 將為 undefined

修改 AddPost 組件中的 AddPost 方法以包含 id 狀態變量。

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

在 addPost API 方法中,您需要檢查 id 參數是否為 undefined 。如果undefined,則表示這是一個新帖子,否則需要調用update方法。 addPost API 方法如下所示:

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

在 post.js 文件中,創建一個名為 updatePost 的方法來更新博客文章詳細信息。您將利用 updateOne API 來更新具有特定 id 的博客文章的詳細信息。以下是 updatePost 方法的外觀:

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 END
喜歡就支持一下吧
點贊15 分享