【发布时间】:2014-08-12 02:41:56
【问题描述】:
我是新手,我正在尝试构建一些东西来学习它的概念。
我创建了一些 react 组件,但无法弄清楚为什么我的 Post 组件在 JSON 请求成功完成后没有被呈现。
注意:Posts 和 PostList 组件的渲染没有问题。
我在这里错过了什么?
/** @jsx React.DOM */
var Posts = React.createClass({
render: function() {
return (
<div className="posts">
<h3>Featured Jobs</h3>
<PostList />
<p>More Awesome Jobs →</p>
</div>
)
}
});
var PostList = React.createClass({
getInitialState: function() {
return { posts: [
] };
},
componentDidMount: function() {
$.getJSON('/api/posts', function(results) {
this.setState({
posts: results
});
}.bind(this));
},
render: function() {
var posts = this.state.posts.map(function(post) {
return <PostListItem post={post} />;
});
return <ul className='post-list'>{posts}</ul>;
}
});
var PostListItem = React.createClass({
handleClick: function(e) {
var post_id = this.props.post.id;
var path = '/api/posts/' + post_id;
$.getJSON(path, function(post) {
return <Post title={post.title} location={post.location} description={post.description} />;
});
},
render: function() {
return (
<div className="post-item">
<li key={this.props.post.id}><a href="#" onClick={this.handleClick}>{this.props.post.title}</a></li>
</div>
);
}
});
var Post = React.createClass({
render: function() {
return(
<div className="post">
<h1>{this.props.title}</h1>
<h2>{this.props.location}</h2>
<p>{this.props.description}</p>
</div>
);
}
});
ps:我正在通过 rails helper 渲染 Posts 组件,但您可以假设它工作正常。
提前谢谢你:)
【问题讨论】:
-
您在 UL 中渲染 DIV。另外,在
$.getJSON回调函数中返回 Post 组件时会发生什么? -
@David 感谢您的回复。我想在 Posts 组件上渲染 Post 组件。也就是说,避免重定向到帖子详情页面。