使用 reactjs,更新列表中的项目而不更新整个列表?

Using reactjs, updating an item in a list without updating the whole list?

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

我对国家应该走向何方感到困惑。我把状态放在 CommentsList 的顶部。以 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>
    );
  }

});

最好的办法是更改此行:

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

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

因为 React 使用键来确定某些内容是否已更改,通过使用迭代器,将新元素添加到评论列表末尾以外的任何位置都需要 React 重新呈现每个评论。

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

"I think this is best practice. Because you are looping through the commentlist with map but react only performs the necessary DOM operations. Some JS loops are faster than more DOM operations." – 达斯汀霍夫纳