我使用React和Reflux。而且我很难弄清楚如何在评论列表中更新一条评论。
我对状态应该去哪里感到困惑。我把状态放在CommentsList的顶部。认为它是反应方式。然后,CommentsItem只是道具。然后每个CommentsItem都有一个LikeButton,我也制作道具。
问题是当我在LikeButton中调用like操作时,它会重新加载CommentsStore中的所有注释。我猜我需要一个新商店来加载一条评论而不是所有评论?但这是否意味着我将状态置于CommentsItem中?我对这里的最佳做法感到困惑。
我正在与之合作:
<ProfilePage />
<div>
<ProfileBox profile={this.state.profile} />
<CommentsList query={{profile: this.state.profile._id}} />
</div>
<CommentsList />
var CommentsList = React.createClass({
mixins: [
Reflux.connect(CommentsStore, 'comments')
],
componentWillMount: function() {
CommentsActions.load(this.props.query);
},
render: function() {
var commentNodes = this.state.comments.map(function (comment, i) {
return (
<CommentsItem key={i} comment={comment} />
);
});
return (
<div>
{commentNodes}
</div>
);
}
});
<CommentsItem />
var CommentsItem = React.createClass({
render: function() {
return (
<div>
<div>
{this.props.comment.user.username}:
{this.props.comment.comment}
</div>
<div>
{this.props.comment.numPoints} people like this
</div>
<div>
OTHER LINKS
<LikeButton commentId={this.props.comment._id} liked={this.props.comment.liked} />
</div>
</div>
);
}
});
<LikeButton />
var LikeButton = React.createClass({
handleLike: function(e) {
e.preventDefault();
CommentsActions.like(this.props.commentId);
},
render: function() {
var likeText = this.props.liked ? 'Unlike' : 'Like';
return(
<a href="#" onClick={this.handleLike}>{likeText}</a>
);
}
});
答案 0 :(得分:1)
“我认为这是最佳实践。因为您使用map循环遍历注释列表,但反应只执行必要的DOM操作。一些JS循环比更多DOM操作更快。” - 达斯汀霍夫纳
答案 1 :(得分:0)
最好的办法是改变这一行:
<CommentsItem key={i} comment={comment} />
到
<CommentsItem key={comment._id} comment={comment} />
由于react使用键来确定某些内容是否已更改,通过使用迭代器,将新元素添加到除评论列表末尾之外的任何位置都需要响应以重新呈现每条评论。
请参阅此处:https://facebook.github.io/react/docs/multiple-components.html#dynamic-children了解详情。