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

使用React创建博客应用:个人资料页面

在本教程系列的一部分中,您看到了如何为我们的 react 博客应用程序实现更新和删除帖子功能。在本教程中,您将为博客应用程序实现个人资料页面。

入门

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

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

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

cd ReactBlogApp-EditDelete npm install

启动节点.js 服务器,您将在 http://localhost:7777/index.html#/运行应用程序。

创建个人资料页面视图

首先,您需要在主页菜单中添加一个名为Profile在 页面上,为 Profile 页面home.html添加一个新元素,如下所示:ul

<ul class="nav nav-pills pull-right"> 
    <li role="presentation" id="homeHyperlink" class="active"><a href="#">首页</a></li> 
    < li role="presentation" id="addHyperLink"><a href="/home#/addpost">添加</a></li> 
    <li role="presentation" id="btnProfile"><a href= "/home#/showProfile">个人资料</a></li> 
    <li role="presentation"><a href="#">注销</a></li> </ul>

保存上述更改并服务器恢复正常。将浏览器指向 http://localhost:7777/ 并登录到应用程序。登录后,您将能够查看带有个人资料链接的菜单列表。

使用React创建博客应用:个人资料页面  第1张

要使配置文件菜单链接起作用,您需要向文件中的现有路由添加新路由。home.jsx

React dom .render( 
    <Router history={hashHistory}> 
        <Route component={ShowPost} path="/"></Route> 
        <Route component={AddPost} path="/addPost(/:id)">< /Route> 
        <Route component={ShowProfile} path="/showProfile"></Route> 
    </Router>, document.getElementById('app'));

在 home.jsx文件中,创建一个新组件ShowProfilename为、passwordemail添加一些状态变量IdShowProfile组件的 render 方法中,添加用于呈现配置文件详细信息的 HTML。这是ShowProfile组件的外观:

class ShowProfile extends React.Component {    constructor(props) {
      super(props);
      this.state = {
        name:'',
        email:'',
        password:'',
        id:''
      };
      
    }
    componentDidMount(){
      document.getElementById('addHyperLink').className = "";
      document.getElementById('homeHyperlink').className = "";
      document.getElementById('profileHyperlink').className = "active";
      this.getProfile();
    }
    updateProfile(){
      
    }

    getProfile(){

    }
    
    render() {
      return (
        <div className="col-md-5">
          <div className="form-area">  
              <form role="form">
                <br styles="clear:both" />
                <div className="form-group">
                  <input value={this.state.name} type="text" onChange={this.handleNameChange} className="form-control" placeholder="Name" required />
                </div>
                <div className="form-group">
                  <input value={this.state.password} type="password" onChange={this.handlePasswordChange} className="form-control" placeholder="Password" required />
                </div>
               
                <button type="button" onClick={this.updateProfile} id="submit" name="submit" className="btn btn-primary pull-right">Update</button>
              </form>
          </div>
        </div>
      )
    }
}

加载配置文件页面时,您需要从数据库获取详细信息并将其填充到表单中。在组件getProfile内部的方法中添加代码以进行ajax调用以获取有关用户的详细信息。ShowProfile

ax ios .post('/getProfile', { } ) .then( function (response) { 
    }) .catch(function (error) { 
    console.log('error is ',error); });

在响应中收到详细信息后,您需要更新相同的状态变量。这是组件中的getProfile方法ShowProfile

getProfile(){ 
  var self = this; 
  axios.post('/getProfile', { 
  }) 
  .then(function (response) { 
    if(response){ 
      self.setState({name:response.data.name}); 
      self.setState({email:response.data .email}); 
      self.setState({password:response.data.password});   
    } 
  }) 
  .catch(function (error) { 
    console.log('error is ',error); 
  }); }

app.js文件中,创建一个方法来处理来自'方法getProfile的 POST 方法调用文件中的 方法将改为调用以 从数据库中获取详细信息。这是它的外观:ShowProfilegetProfilegetProfileapp.jsuser.js

app.post('/getProfile', function(req,res){ 
  user.getUserInfo(sessions.username, function(result){ 
    res.send(result) 
  }) })

user.js文件中,创建一个名为的方法,该方法 getUserInfo将使用用户名查询mongodb数据库以获取所需的详细信息。以下是该getUserInfo方法的外观:

getUserInfo: function(username, callback ){ 
	MongoClient.connect(url, function(err, db){ 
		
		db.collection('user').findOne( { email : username 
		},function(err, result){ 
			if(result= =null){ 
				callback(false) 
			} 
			else{ 
				callback(result); 
			} 
		}); 
        
	}); }

如上面的代码所示,您使用 MongoDB 调用以MongoClient根据电子邮件地址查询用户集合。收到结果后,将其返回给回调函数。 

保存上述更改并重新启动 node.js 服务器。将浏览器指向 http://localhost:7777/#/ 并登录到应用程序。单击菜单中的配置文件链接,您将能够查看页面上填充的配置文件详细信息。

使用React创建博客应用:个人资料页面  第2张

更新用户配置文件

要处理名称和密码的更改,您需要 在组件中定义两个方法调用handleNameChange和 这些方法将在文本更改时设置状态变量。这是它的外观:handlePasswordChangeShowProfile

handleNameChange(e){ 
  this.setState({name:e.target.value}) } handlePasswordChange(e){ 
  this.setState({password:e.target.value}) }

绑定ShowProfile构造函数中的方法。

constructor(props) {
  super(props);
  this.handleNameChange = this.handleNameChange.bind(this);
  this.handlePasswordChange = this.handlePasswordChange.bind(this);
  this.updateProfile = this.updateProfile.bind(this);
  this.getProfile = this.getProfile.bind(this);
  this.state = {
    name:'',
    email:'',
    password:'',
    id:''
  };
  
}

定义一个方法updateProfile,当用户单击Update按钮更新用户详细信息时将调用该方法。在方法内部,对文件中updateProfile的方法进行 POST 调用 以及更改的以下是组件中的方法的外观:updateProfileapp.jsnamepasswordupdateProfileShowProfile

updateProfile(){ 
  var self = this; 
  axios.post('/updateProfile', { 
    name: this.state.name, 
    password: this.state.password 
  }) .then 
  (function (response) { 
    if(response){ 
      hashHistory.push('/')   
    } 
  } ) 
  .catch(function (error) { 
    console.log('error is ',error); 
  }); }

一旦收到来自 POST 调用的响应,屏幕就会导航到博客文章列表。

在该 app.js文件中,创建一个名为的方法,该方法updateProfile将解析传入的参数并调用 MongoDB 数据库

app.post('/updateProfile', function(req, res){ 
  var name = req.body.name; 
  var password = req.body.password; 
  
  user.updateProfile(name, password, sessions.username, function(result) { 
      res.send(result); 
  }) })

从上面的代码中可以看出,一旦在文件 中的updateProfile方法中 解析了参数,就会使用 changed 和 调用该方法。 app.jsuser.updateProfilenamepasswordusername

让我们在文件中定义user.updateProfile方法user.js,它将调用MongoDB 数据库namepassword根据username以下是文件中updateProfile方法的user.js外观:

updateProfile: function(name, password, username, callback){ 
	MongoClient.connect(url, function(err, db) { 
	  	db.collection('user').updateOne( 
	  		{ "email": username }, 
	  		{ $set: 
	  			{ "name" : 名称, 
	  			  "password" : 密码
	  			} 
	  		},function(err, result){ 
			
	    	if(err == null){ 
	    		callback(true) 
	    	} 
	    	else{ 
	    		callback(false) 
	    	} 
		}); 
	}); }

updateOne在上面的代码中,您使用该方法根据电子邮件地址更新了用户详细信息。

保存上述更改并重新启动服务器。登录到应用程序并单击配置文件链接。更改名称和密码,然后单击更新按钮。尝试登录,您将能够使用新密码登录。 



文章目录
  • 入门
  • 创建个人资料页面视图
  • 更新用户配置文件