亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
start using
Create update and delete views
Implement update release function
實現(xiàn)刪除帖子功能
總結(jié)
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

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 的博客應(yīng)用程序中更新和刪除帖子:第 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 的博客應(yīng)用程序中更新和刪除帖子:第 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)
	    	}
		});
	});
}

保存以上更改并重新啟動服務(wù)器。登錄應(yīng)用程序并點(diǎn)擊編輯圖標(biāo)。修改現(xiàn)有值并單擊按鈕更新詳細(xì)信息。

實現(xiàn)刪除帖子功能

要實現(xiàn)刪除帖子功能,您需要將點(diǎn)擊事件附加到刪除圖標(biāo)。修改刪除圖標(biāo)跨度如圖:

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

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

ShowPost 組件中創(chuàng)建一個名為 deletePost 的方法。

deletePost(id){
      
}

ShowPost組件構(gòu)造函數(shù)中綁定該方法。

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

要在 map 函數(shù)回調(diào)中使用 this,您需要將 this 綁定到 map 函數(shù)。修改map函數(shù)回調(diào)如圖:


      {
        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 方法中,在調(diào)用刪除 API 之前添加確認(rèn)提示。

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

現(xiàn)在讓我們在 app.js 文件中添加 deletePost API。 API 將從 AJAX 調(diào)用中讀取帖子 ID 并從 MongoDB 中刪除該條目。以下是 deletePost API 的外觀:

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

如上面的代碼所示,您將調(diào)用 post.js 文件中的 deletePost 方法并返回結(jié)果。讓我們在 post.js 文件中創(chuàng)建 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 中的博客數(shù)據(jù)庫。使用從 AJAX 調(diào)用傳遞的 Id ,它將從數(shù)據(jù)庫中刪除該帖子。

更新 home.jsx 文件中 deletePost 方法內(nèi)的代碼,以包含對 deletePost API 的 AJAX 調(diào)用 app.js 文件。

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

刪除博客文章后,您需要刷新博客文章列表以反映這一點(diǎn)。因此,創(chuàng)建一個名為 getPost 的新方法,并將 componentDidMount 代碼移到該函數(shù)內(nèi)。這是 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 調(diào)用成功回調(diào)內(nèi),調(diào)用 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);
    });
  }
}

保存以上更改并重新啟動服務(wù)器。嘗試添加新的博客文章,然后從網(wǎng)格列表中單擊“刪除”。系統(tǒng)將提示您一條刪除確認(rèn)消息。單擊確定按鈕后,該條目將被刪除,并且博客文章列表將被更新。

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

總結(jié)

在本教程中,您了解了如何在 React 博客應(yīng)用程序中實現(xiàn)刪除和更新博客文章功能。在本教程系列的下一部分中,您將了解如何為登錄用戶實現(xiàn)個人資料頁面。

請在下面的評論中告訴我們您的想法和建議。本教程的源代碼可在 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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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)

How to diagnose high CPU usage caused by WordPress How to diagnose high CPU usage caused by WordPress Jul 06, 2025 am 12:08 AM

The main reasons why WordPress causes the surge in server CPU usage include plug-in problems, inefficient database query, poor quality of theme code, or surge in traffic. 1. First, confirm whether it is a high load caused by WordPress through top, htop or control panel tools; 2. Enter troubleshooting mode to gradually enable plug-ins to troubleshoot performance bottlenecks, use QueryMonitor to analyze the plug-in execution and delete or replace inefficient plug-ins; 3. Install cache plug-ins, clean up redundant data, analyze slow query logs to optimize the database; 4. Check whether the topic has problems such as overloading content, complex queries, or lack of caching mechanisms. It is recommended to use standard topic tests to compare and optimize the code logic. Follow the above steps to check and solve the location and solve the problem one by one.

How to minify JavaScript files in WordPress How to minify JavaScript files in WordPress Jul 07, 2025 am 01:11 AM

Miniving JavaScript files can improve WordPress website loading speed by removing blanks, comments, and useless code. 1. Use cache plug-ins that support merge compression, such as W3TotalCache, enable and select compression mode in the "Minify" option; 2. Use a dedicated compression plug-in such as FastVelocityMinify to provide more granular control; 3. Manually compress JS files and upload them through FTP, suitable for users familiar with development tools. Note that some themes or plug-in scripts may conflict with the compression function, and you need to thoroughly test the website functions after activation.

How to optimize WordPress without plugins How to optimize WordPress without plugins Jul 05, 2025 am 12:01 AM

Methods to optimize WordPress sites that do not rely on plug-ins include: 1. Use lightweight themes, such as Astra or GeneratePress, to avoid pile-up themes; 2. Manually compress and merge CSS and JS files to reduce HTTP requests; 3. Optimize images before uploading, use WebP format and control file size; 4. Configure.htaccess to enable browser cache, and connect to CDN to improve static resource loading speed; 5. Limit article revisions and regularly clean database redundant data.

How to use the Transients API for caching How to use the Transients API for caching Jul 05, 2025 am 12:05 AM

TransientsAPI is a built-in tool in WordPress for temporarily storing automatic expiration data. Its core functions are set_transient, get_transient and delete_transient. Compared with OptionsAPI, transients supports setting time of survival (TTL), which is suitable for scenarios such as cache API request results and complex computing data. When using it, you need to pay attention to the uniqueness of key naming and namespace, cache "lazy deletion" mechanism, and the issue that may not last in the object cache environment. Typical application scenarios include reducing external request frequency, controlling code execution rhythm, and improving page loading performance.

How to prevent comment spam programmatically How to prevent comment spam programmatically Jul 08, 2025 am 12:04 AM

The most effective way to prevent comment spam is to automatically identify and intercept it through programmatic means. 1. Use verification code mechanisms (such as Googler CAPTCHA or hCaptcha) to effectively distinguish between humans and robots, especially suitable for public websites; 2. Set hidden fields (Honeypot technology), and use robots to automatically fill in features to identify spam comments without affecting user experience; 3. Check the blacklist of comment content keywords, filter spam information through sensitive word matching, and pay attention to avoid misjudgment; 4. Judge the frequency and source IP of comments, limit the number of submissions per unit time and establish a blacklist; 5. Use third-party anti-spam services (such as Akismet, Cloudflare) to improve identification accuracy. Can be based on the website

How to use the Plugin Check plugin How to use the Plugin Check plugin Jul 04, 2025 am 01:02 AM

PluginCheck is a tool that helps WordPress users quickly check plug-in compatibility and performance. It is mainly used to identify whether the currently installed plug-in has problems such as incompatible with the latest version of WordPress, security vulnerabilities, etc. 1. How to start the check? After installation and activation, click the "RunaScan" button in the background to automatically scan all plug-ins; 2. The report contains the plug-in name, detection type, problem description and solution suggestions, which facilitates priority handling of serious problems; 3. It is recommended to run inspections before updating WordPress, when website abnormalities are abnormal, or regularly run to discover hidden dangers in advance and avoid major problems in the future.

How to enqueue assets for a Gutenberg block How to enqueue assets for a Gutenberg block Jul 09, 2025 am 12:14 AM

When developing Gutenberg blocks, the correct method of enqueue assets includes: 1. Use register_block_type to specify the paths of editor_script, editor_style and style; 2. Register resources through wp_register_script and wp_register_style in functions.php or plug-in, and set the correct dependencies and versions; 3. Configure the build tool to output the appropriate module format and ensure that the path is consistent; 4. Control the loading logic of the front-end style through add_theme_support or enqueue_block_assets to ensure that the loading logic of the front-end style is ensured.

How to add custom fields to users How to add custom fields to users Jul 06, 2025 am 12:18 AM

To add custom user fields, you need to select the extension method according to the platform and pay attention to data verification and permission control. Common practices include: 1. Use additional tables or key-value pairs of the database to store information; 2. Add input boxes to the front end and integrate with the back end; 3. Constrain format checks and access permissions for sensitive data; 4. Update interfaces and templates to support new field display and editing, while taking into account mobile adaptation and user experience.

See all articles