我正在使用 React 和 Reflux。我很难弄清楚如何更新评论列表中的一条评论。
我对状态应该去哪里感到困惑。我将状态放在 CommentsList 的顶部。以 React 的方式思考。然后 CommentsItem 只是 Prop 。然后每个 CommentsItem 都有一个 LikeButton,我也制作了 props。
问题是当我在 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>
);
}
});
最佳答案
最好的办法是更改这一行:
<CommentsItem key={i} comment={comment} />
至
<CommentsItem key={comment._id} comment={comment} />
由于 React 使用键来确定某些内容是否已更改,因此通过使用迭代器,将新元素添加到除评论列表末尾之外的任何位置都需要 React 重新渲染每个评论。
请参阅此处:https://facebook.github.io/react/docs/multiple-components.html#dynamic-children了解更多详情。
关于javascript - 使用reactjs,更新列表中的项目而不更新整个列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29717842/