class CommentArea extends React.Component{ constructor(props) { super(props) this.state = { comments:[] } this.handleComment=this.handleComment.bind(this) this.onDelete=this.onDelete.bind(this) } handleComment(value) { this.setState({ comments:[...this.state.comments,value] }) } onDelete(deleteIndex) { console.log(this.state.comments) console.log(deleteIndex) this.setState({ comments: this.state.comments.filter((item,index) => {return index != deleteIndex}) }) console.log(this.state.comments) } render() { const comments = this.state.comments return( <div> <CommentList comments={comments} onDelete={this.onDelete}></CommentList> <CommentBox2 commentsLength={comments.length} onHandleComment={this.handleComment }></CommentBox2> </div> ) } } export default CommentArea
点击删除留言时,界面已经删除相应留言,但是对于state里comments数组元素的日志输出始终慢一个节拍。
原始效果
点击删除2 界面及后日志输出
点击删除3 界面及后日志输出
因为 this.setState 方法是异步的,可以参考这篇文章 https://segmentfault.com/a/1190000013040438?utm_source=tag-newest