【问题标题】:Using reactjs, updating an item in a list without updating the whole list?使用reactjs,更新列表中的项目而不更新整个列表?
【发布时间】:2015-06-25 09:43:22
【问题描述】:

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

我对国家应该去哪里感到困惑。我把状态放在评论列表的顶部。以 React 方式思考。然后 CommentsItem 只是道具。然后每个 CommentsItem 都有一个 LikeButton,我也做了 props。

问题是当我在 LikeButton 中调用 like 操作时,它会重新加载 CommentsStore 中的所有 cmets。我猜我需要一个加载一个 cmets 而不是所有 cmets 的新商店?但这是否意味着我将状态置于 CommentsItem 中?我对这里的最佳做法有点困惑。

这就是我正在使用的:

<ProfilePage />

<div>
    <ProfileBox profile={this.state.profile} />
    <CommentsList query={{profile: this.state.profile._id}} />
</div>

&lt;CommentsList /&gt;

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>
    );
  }

});

&lt;CommentsItem /&gt;

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>
    );
  }
});

&lt;LikeButton /&gt;

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>
    );
  }

});

【问题讨论】:

  • 我认为这是最佳实践。因为您正在使用 map 循环浏览评论列表,但 react 只执行必要的 DOM 操作。一些 JS 循环比更多的 DOM 操作更快。
  • 哦,我是个白痴。我看到它正在更新其他一些帖子的时间字段,所以我认为它正在更新所有帖子。太棒了,它只更新必要的!非常感谢

标签: javascript reactjs reactjs-flux refluxjs


【解决方案1】:

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

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

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

因为 react 使用 key 来确定是否发生了变化,通过使用迭代器,将新元素添加到除了 cmets 列表末尾之外的任何地方都需要 react 来重新呈现每条评论。

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

【讨论】:

  • 如果评论列表已经是{'id1': {...}, 'id2': {...} }的对象,这是没用的
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-04
    • 1970-01-01
    • 2018-12-06
    • 2017-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-20
    相关资源
    最近更新 更多