React.js 小书 Lesson26 - 实战分析:评论功能(五)
React.js 小书 Lesson26 - 实战分析:评论功能(五)
转载请注明出处,保留原文链接以及作者信息 在线阅读:http://huziketang.com/books/react 持久化评论同样地,可以通过类似于用户名持久化的方式对评论列表内容进行持久化,让用户发布的评论在刷新页面以后依然可以存在。修改 class CommentApp extends Component { constructor () { super() this.state = { comments: [] } } componentWillMount () { this._loadComments() } _loadComments () { let comments = localStorage.getItem('comments') if (comments) { comments = JSON.parse(comments) this.setState({ comments }) } } _saveComments (comments) { localStorage.setItem('comments',JSON.stringify(comments)) } handleSubmitComment (comment) { if (!comment) return if (!comment.username) return alert('请输入用户名') if (!comment.content) return alert('请输入评论内容') const comments = this.state.comments comments.push(comment) this.setState({ comments }) this._saveComments(comments) } ... 我们增加了 现在发布评论,然后刷新可以看到我们的评论并不会像以前一样消失。非常的不错,持久化评论的功能也完成了。 显示评论发布时间现在我们给每条评论都加上发布的日期,并且在评论列表项上显示已经发表了多久,例如“1 秒前”、“30分钟前”,并且会每隔 5 秒进行更新。修改 ... handleSubmit () { if (this.props.onSubmit) { this.props.onSubmit({ username: this.state.username,content: this.state.content,createdTime: +new Date() }) } this.setState({ content: '' }) } ... 在评论列表项上显示评论,修改 class Comment extends Component { static propTypes = { comment: PropTypes.object.isRequired } constructor () { super() this.state = { timeString: '' } } componentWillMount () { this._updateTimeString() } _updateTimeString () { const comment = this.props.comment const duration = (+Date.now() - comment.createdTime) / 1000 this.setState({ timeString: duration > 60 ? `${Math.round(duration / 60)} 分钟前` : `${Math.round(Math.max(duration,1))} 秒前` }) } render () { return ( <div className='comment'> <div className='comment-user'> <span>{this.props.comment.username} </span>: </div> <p>{this.props.comment.content}</p> <span className='comment-createdtime'> {this.state.timeString} </span> </div> ) } } 每个 再看看页面显示:
这时候的时间是不会自动更新的。除非你手动刷新页面,否则永远显示“1 秒前”。我们可以在 ... componentWillMount () { this._updateTimeString() this._timer = setInterval( this._updateTimeString.bind(this),5000 ) } ... 这样就可以做到评论的发布时间自动刷新了,到这里前 4 个需求都已经完成了。 下一节中我们将介绍《React.js 小书 Lesson27 - 实战分析:评论功能(六)》。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |