问题在于这条线:
{this.props.postComments.map( this.renderComment )}因为您忘记了绑定
renderComment,映射回调方法,所以
thisinside
renderComment方法将不会引用类上下文。
使用这些解决方案中的 任何一种 ,它将起作用。
1- 在
constructor以下位置使用此行:
this.renderComment = this.renderComment.bind(this) ;
2- 通过
this与
map喜欢:
{this.props.postComments.map(this.renderComment, this)}3- 将Arrow函数与
renderComment方法配合使用,如下所示:
renderComment = (comment, i) => { .....或在
renderComment函数内部使用地图(我以前更喜欢这种方式),如下所示:
renderComment() { return this.props.postComments.map((comment, i) => { return( <div className="comment" key={i}> <p> <strong>{comment.user}</strong> {comment.text} <button onClick={this.handleRemoveComment} className="remove-comment"> × </button> </p> </div> ) })}并从中调用此方法
render,在这种情况下,
renderComment不需要绑定:
{this.renderComment()}


