我正在尝试使用 React、Express、MongoDB 和 Node 构建一个简单的博客。但我仍然对(1)如何正确向数据库发出 ajax 请求以及如何设置状态和(2)如何正确更新状态感到困惑。
我尝试通过发出 AJAX 请求来设置 getInitialState,但它不起作用。我也不知道这是否是最佳实践。另外,一旦有人添加了新帖子,我应该将帖子放在哪里,然后如何正确更新状态?
var React = require('react');
var List = React.createClass({
render: function() {
return (
<div>
<h2>{this.props.postbody}</h2>
</div>
)
}
})
// I'll break this up into smaller components later, but for now I just want
// to know where to put my database entries into the posts array.
// The only field in MongoDB right now is postbody.
var Home = React.createClass({
getInitialState: function() {
return {
posts: []
}
},
handleClick: function() {
$.ajax({
type: 'GET',
url: '/api/blogPosts',
success: function(data) {
this.setState = data;
console.log(this.setState);
}
})
},
render: function() {
return (
<div>
{this.state.posts.map(function(post) {
return (
<List postbody={post.postbody}></List>
)
})}
</div>
)
}
})
最佳答案
setState 是一个函数,而不是要在 this
上设置的属性。你应该这样做 this.setState(data)
关于javascript - 如何从 MongoDB 中提取项目并在输入新项目时更新它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33795557/