gpt4 book ai didi

ajax - 使用react nodejs和ajax更新mongodb的文档

转载 作者:太空宇宙 更新时间:2023-11-03 23:36:59 24 4
gpt4 key购买 nike

嗨,我开始使用 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
});
});

现在进行 react 部分:

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

除非您可能有一个表单或其他东西,甚至是另一个处理添加新用户的类。这个问题看起来非常广泛,所以我只是概述了我将如何做到这一点!

关于ajax - 使用react nodejs和ajax更新mongodb的文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30976158/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com