在本教學系列的前一部分中,您了解如何實現新增和顯示貼文功能。在有關在 React 中建立部落格應用程式的教學系列的這一部分中,您將實現更新和刪除部落格文章的功能。
開始使用
讓我們開始複製本系列最後一部分的原始碼。
https://github.com/royagasthyan/ReactBlogApp-AddPost
克隆目錄後,導覽至專案目錄並安裝所需的依賴項。
cd ReactBlogApp-AddPost npm install
啟動 Node.js 伺服器,應用程式將在 http://localhost:7777/index.html#/ 上運行。
建立更新和刪除視圖
讓我們修改部落格文章列表,以帶有更新和刪除圖示的表格形式顯示資料。在 ShowPost
元件的 render 方法中,將現有的 div
替換為表格,如程式碼所示:
<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>
如上面的程式碼所示,您已修改現有程式碼以以表格形式顯示貼文。您已對應 posts
變數以迭代 posts 集合並動態建立所需的 tr
和 td
。
儲存以上變更並重新啟動伺服器。將瀏覽器指向 http://localhost:7777/home#/,您應該可以以表格格式查看部落格文章清單。
實作更新發布功能
要實現更新發布功能,您需要將點擊事件附加到編輯圖示。修改編輯圖示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 的部落格文章的詳細資訊。
儲存以上變更並嘗試執行程式。點擊主頁上的編輯圖標,它將重定向到添加帖子頁面並填充標題和主題。
現在,要更新部落格文章詳細信息,您需要檢查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}.bind(this)) } {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>
在 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 博客应用程序中实现删除和更新博客文章功能。在本教程系列的下一部分中,您将了解如何为登录用户实现个人资料页面。
请在下面的评论中告诉我们您的想法和建议。本教程的源代码可在 GitHub 上获取。
以上是在基於 React 的部落格應用程式中更新和刪除帖子:第 4 部分的詳細內容。更多資訊請關注PHP中文網其他相關文章!

WordPressIsAcmsDuetoItseAsofuse,自定義,USERMANAMECTION,SEO和COMMUNITYSUPPORT.1)ITSIMPLIFIESCONTENTMANGAMEWITHANINTUISIDERFEEFFECE.2)提供extentensiveCustomizationThroughThroughTheMesandPlugins.3)supportrobustuserrolesandplugins.4)supportrobustuserrolesandpermissions.4)增強

在 WordPress 網站上啟用評論功能,可以為訪客提供參與討論和分享反饋的平台。為此,請按照以下步驟操作:啟用評論:在儀錶盤中,導航至“設置”>“討論”,並選中“允許評論”複選框。創建評論表單:在編輯器中,單擊“添加塊”並蒐索“評論”塊,將其添加到內容中。自定義評論表單:通過設置標題、標籤、佔位符和按鈕文本來定制評論塊。保存更改:單擊“更新”以保存評論框並將其添加到頁面或文章中。

如何復制 WordPress 子站?步驟:在主站創建子站。在主站克隆子站。將克隆導入目標位置。更新域名(可選)。分開插件和主題。

在WordPress中創建自定義頁頭的步驟如下:編輯主題文件“header.php”。添加您的網站名稱和描述。創建導航菜單。添加搜索欄。保存更改並查看您的自定義頁頭。

WordPress 網站中啟用評論功能:1. 登錄管理面板,轉到 "設置"-"討論",勾選 "允許評論";2. 選擇顯示評論的位置;3. 自定義評論表單;4. 管理評論,批准、拒絕或刪除;5. 使用 <?php comments_template(); ?> 標籤顯示評論;6. 啟用嵌套評論;7. 調整評論外形;8. 使用插件和驗證碼防止垃圾評論;9. 鼓勵用戶使用 Gravatar 頭像;10. 創建評論指

可以通過 WordPress 安裝 FTP 插件,配置 FTP 連接,然後使用文件管理器上傳源碼。步驟包括:安裝 FTP 插件、配置連接、瀏覽上傳位置、上傳文件、檢查上傳成功。

如何復制 WordPress 代碼?從管理界面複製:登錄 WordPress 網站,導航到目標位置,選擇代碼並按 Ctrl C (Windows)/Command C (Mac) 複製代碼。從文件複製:使用 SSH 或 FTP 連接到服務器,導航到主題或插件文件,選擇代碼並按 Ctrl C (Windows)/Command C (Mac) 複製代碼。

WordPress 錯誤解決指南:500 內部服務器錯誤:禁用插件或檢查服務器錯誤日誌。 404 未找到頁面:檢查 permalink 並確保頁面鏈接正確。白屏死機:增加服務器 PHP 內存限制。數據庫連接錯誤:檢查數據庫服務器狀態和 WordPress 配置。其他技巧:啟用調試模式、檢查錯誤日誌和尋求支持。預防錯誤:定期更新 WordPress、僅安裝必要插件、定期備份網站和優化網站性能。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

Atom編輯器mac版下載
最受歡迎的的開源編輯器

MinGW - Minimalist GNU for Windows
這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

禪工作室 13.0.1
強大的PHP整合開發環境

WebStorm Mac版
好用的JavaScript開發工具