【发布时间】:2015-11-19 23:16:33
【问题描述】:
我正在使用 React、MongoDB、Express 和 Node 创建博客。我有三个组件:App、List 和 Item。该项目是一篇博客文章;该列表是博客文章的列表,该应用程序包含一个输入文本并提交的地方。我最终会添加更多功能,但我想确定我是否遵守 React 的最佳实践(我怀疑我是)。
所以在 App 中,我使用一组帖子 (posts) 和一个输入文本字符串 (postbody) 来获取初始状态。我使用 componentDidMount 向我的数据库发出 AJAX GET 请求,因此用户可以看到所有帖子。
为了处理输入的文本,我只是做了一个简单的 handleChange 函数来更新 postbody 的状态。
我还有一个 handleClick 函数,它获取 this.state.postbody 然后将其发布到数据库中。然而,相同的函数也会对数据库发出单独的 GET 请求以更新帖子数组的状态。这似乎不对!不应该以其他方式处理并自动更新吗? * 这是我的主要问题。 *
另外,如果我需要进一步分解组件,或者我是否违反了使用 React 的最佳实践(例如,在错误的位置更改状态,或不正确地使用 props),请告诉我。
var React = require('react');
var Item = React.createClass({
render: function() {
return (
<div>
<h2>{this.props.postbody}</h2>
</div>
)
}
})
var List = React.createClass({
render: function() {
return (
<div>
{this.props.array.map(function(post) {
return (
<Item postbody={post.postbody}></Item>
)
})}
</div>
)
}
})
var App = React.createClass({
getInitialState: function() {
return {
posts: [],
postbody: ''
}
},
componentDidMount: function() {
$.ajax({
type: 'GET',
url: '/api/blogPosts',
success: function(data) {
this.setState({posts: data});
}.bind(this)
})
},
handleClick: function() {
event.preventDefault();
var blogPost = this.state.postbody;
$.ajax({
type: 'POST',
url: '/api/blogPosts',
data: { postbody: blogPost }
});
$.ajax({
type: 'GET',
url: '/api/blogPosts',
success: function(data) {
this.setState({posts: data});
}.bind(this)
})
},
handleChange: function(event) {
this.setState({ postbody: event.target.value})
},
render: function() {
return (
<div>
<form action="/api/blogPosts" method="post">
<input onChange={this.handleChange} type="text" name="postbody"></input>
<button type="button" onClick={this.handleClick}>Submit</button>
</form>
<List array={this.state.posts} />
</div>
)
}
})
【问题讨论】:
-
“React 最佳实践”取决于您遵循的数据模式。你看过 Flux 或 Redux 吗?