• 日常搜索
  • 百度一下
  • Google
  • 在线工具
  • 搜转载

使用React创建博客应用:更新和删除帖子

在本教程系列的前一部分 中,您了解了如何实现添加和显示帖子功能。在关于在 react 中创建博客应用程序的教程系列的这一部分中,您将实现更新和删除博客文章的功能。

入门

让我们从克隆本系列最后一部分的源代码开始。

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

克隆目录后,导航到项目目录并安装required 依赖项。

cd ReactBlogApp-AddPost
npm install

启动节点.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为迭代帖子集合并动态创建所需的tr和td。

保存上述更改并让服务器恢复正常。将浏览器指向 http://localhost:7777/home#/  ,您应该能够以表格格式查看博客文章列表。

使用React创建博客应用:更新和删除帖子  第1张

实现更新发布功能

要实现更新发布功能,您需要将点击事件附加到编辑图标。修改编辑图标span如图: 

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

如上面的代码所示,您已将 post id 作为参数传递给该updatePost方法。

updatePost在组件内部创建一个方法ShowPost。

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

如上面的代码所示,您已触发重定向到带有已编辑项目 id 的添加帖子页面。在添加帖子页面中,您将使用传递的 id 获取博客帖子的详细信息并填充详细信息。

修改路由器以在添加帖子页面中包含可选的 id 参数。

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

在AddPost组件内部,创建一个调用方法getPostWithId来获取博客文章的详细信息id。在getPostWithId方法内部,对内部的api进行ajax调用。getPostWithId 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);
  });
}

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>

现在让我们在 getPostWithId 内部创建 API 以对mongodbapp.js数据库进行 数据库调用,  以获取具有特定 Id 的帖子详细信息。这是API方法:getPostWithId

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

如上面的代码所示,您已经使用findOneAPI 来获取具有特定 Id 的博客文章的详细信息。

保存上述更改并尝试运行该程序。单击主页上的编辑图标,它将重定向到添加帖子页面并填充标题和主题。

使用React创建博客应用:更新和删除帖子  第2张

现在,要更新博客文章详细信息,您需要id检查addPost. app.js如果是新帖子,id则为undefined.

修改组件addPost内部的方法AddPost以包含id状态变量。

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

在addPostAPI 方法内部,您需要检查id参数是否undefined存在。如果undefined,则表示它是一个新帖子,否则您需要调用更新方法。addPostAPI 方法如下所示:

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来更新博客文章详细信息的方法。您将使用 updateOneAPI 使用特定的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方法。 

deletePost创建一个在组件内部调用的方法ShowPost。

deletePost(id){
      
}

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

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

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

<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 onClick={this.updatePost.bind(this,post._id)} className="glyphicon glyphicon-pencil"></span>
                    </td>
                    <td>
                      <span onClick={this.deletePost.bind(this,post._id)} className="glyphicon glyphicon-remove"></span>
                    </td>
                  </tr>
        }.bind(this))
      }
 </tbody>

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

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

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

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

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

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

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

更新文件中deletePost方法内的代码以在文件中包含对API的 AJAX 调用。home.jsxdeletePostapp.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 = "";
}

在deletePostAJAX 调用成功回调中,调用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创建博客应用:更新和删除帖子  第3张

最后

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


文章目录
  • 入门
  • 创建更新和删除视图
  • 实现更新发布功能
  • 实现删除帖子功能
  • 最后