[英]Updating documents of mongodb using react nodejs and ajax
Hii我开始使用nodejs练习react和mongodb。 通过使用react我在nodejs的帮助下获取数据...现在,我试图在nodejs的帮助下更新或删除mongodb文档。
我在nodejs中为他们编写了服务,但是我对如何将它与React连接一无所知。
请帮助我克服这个问题。
提前致谢...
如果您访问react网站,并查看他们的教程,那么他们将提供一个很好的ajax调用示例。
基本上,您首先编写ajax函数,因此如果它是GET请求,则可能看起来像这样:
您的nodejs代码:
//the route we get our users at is allUsers
app.get('/allUsers, function(req, res) {
User.find({}, function(err, userarray) { //we grab all users from our mongo collection, and that array of users is called userarray
res.json(userarray); //we return the json with it
});
});
现在到反应部分:
var Users = React.createClass({
getUsers : function() { //we define a function for getting our users
$.ajax({ //call ajax like we would in jquery
url: '/allUsers', //this is the url/route we stored our users on
dataType: 'json',
success: function(data) { //if we get a Success for our http get then..
this.setState({user:data}); //set the state of our user array to whatever the url returned, in this case the json with all our users
}.bind(this),
error: function(xhr, status, err) { //error logging and err tells us some idea what to debug if something went wrong.
console.log("error");
console.error(this.props.url,status, err.toString());
}.bind(this)
});
},
getInitialState: function() { //setting our initial state for our user array we want to use in our react code
return {
users: [], //initialize it empty, or with whatever you want
}
},
componentDidMount : function() {
this.getUsers(); //we are invoking our getUsers function here, therefore performing the ajax call
},
render : function() {
return(
//do what we want to do with our array here I guess!
<div>
<PrintArray users = {this.state.users} />
</div>
)
}
});
//Our new Class called Printarray
var PrintArray = React.createClass({
render : function() {
//Psuedocode
return(
ul {
this.props.users.map(function(user){ //we are mapping all our users to a list, this.props.users is inheritance what we passed down from our Users class
return (
<li key = user.id> user.name </li>
)
})
)
}
</ul>
});
最后,只需要打电话给我们的主要班级,
React.render(<Users />,
document.getElementById(domnNode)); //your div's id goes here
我注释掉了代码,如果您还有其他问题,请随时提出! 我也不知道您是否也想做一个post方法,但是类似。 您只需将GET更改为POST,而不是没有参数的函数,就很可能需要一个参数,因此它可能类似于:
sendNewUser : function(data) {
//do ajax post stuff here
}
并在渲染中:
render : function(){
sendNewUser(blah);
}
除非您可能有一个用于添加新用户的表单,某物或什至另一个类。 这个问题似乎很广泛,所以我只是概述了我将如何做!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.