2

我正在使用 React 和 Reflux。而且我很难弄清楚如何更新评论列表中的一条评论。

我对国家应该去哪里感到困惑。我把状态放在评论列表的顶部。以 React 方式思考。然后 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>
    );
  }

});
4

2 回答 2

1

最好的办法是改变这一行:

<CommentsItem key={i} comment={comment} />

<CommentsItem key={comment._id} comment={comment} />

由于 react 使用 key 来确定是否发生了某些变化,通过使用迭代器,将新元素添加到评论列表末尾以外的任何地方都需要 react 来重新呈现每个评论。

请参阅此处:https ://facebook.github.io/react/docs/multiple-components.html#dynamic-children了解更多详情。

于 2015-04-18T15:44:59.613 回答
1

“我认为这是最佳实践。因为您正在使用 map 循环浏览评论列表,但 react 只执行必要的 DOM 操作。一些 JS 循环比更多 DOM 操作更快。” ——达斯汀霍夫纳

于 2015-06-05T12:15:41.330 回答