2

ReactとRefluxを使用しています。そして、コメントのリスト内の 1 つのコメントを更新する方法を理解するのに苦労しています。

私は州がどこに行くべきかについて混乱しています。私は状態をCommentsListの一番上に置きました。Reactのように考えてください。そして、CommentsItem は単なる小道具です。そして、各 CommentsItem には LikeButton があり、これも小道具として作成しました。

問題は、LikeButton で like アクションを呼び出すと、CommentsStore のすべてのコメントがリロードされることです。すべてのコメントではなく 1 つのコメントを読み込む新しいストアが必要だと思いますか? しかし、それは私がコメント項目に状態を入れているということですか? ここでのベストプラクティスについては、ちょっと混乱しています。

これは私が取り組んでいるものです:

<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} />

反応はキーを使用して何かが変更されたかどうかを判断するため、イテレータを使用して、コメント リストの最後以外の場所に新しい要素を追加すると、すべてのコメントを再レンダリングするために反応が必要になります。

詳細については、 https : //facebook.github.io/react/docs/multiple-components.html#dynamic-childrenを参照してください。

于 2015-04-18T15:44:59.613 に答える