【发布时间】:2016-06-29 17:00:19
【问题描述】:
我正在尝试构建以下内容:一个可以创建帖子的论坛,它会触发 ADD_POST,然后创建帖子,并将其添加到“帖子”对象数组中。每个“post”对象都使用一个“cmets”数组进行初始化,该数组将保存在该帖子中输入的评论文本(“commentTxt”)。
let postReducer = function(posts = [], action) {
switch (action.type) {
case 'ADD_POST':
return [{
id: getId(posts), //just calls a function that provides an id that increments by 1 starting from 0
comments: [
{
id: getId(posts),
commentTxt: ''
}
]
}, ...posts]
然后,当用户输入该帖子时,会有一个评论部分,用户可以在其中输入评论文本,并且将(通过“ADD_COMMENT”)将一个新对象添加到“posts.cmets”数组中
case 'ADD_COMMENT':
return posts.map(function(post){
//find the right 'post' object in the 'posts' array to update the correct 'comments' array.
if(post.id === action.id){
//update 'comments' object array of a 'post' object by adding a new object that contains 'commentTxt', and replaces the current 'comments' array
return post.comments = [{
id: action.id,
//new object is made with text entered (action.commentTxt) and added to 'post.comments' array
commentTxt: action.commentTxt
}, ...post.comments]
}
})
并会显示它。并且每次添加新评论时,都会呈现一个新评论以及数组中先前的评论对象。 想要做如下的事情:
{
this.props.post.comments.map((comment) => {
return <Comment key={comment.id} comment={comment} actions={this.props.actions}/>
})
}
我听说不建议直接改变状态,因此我将不胜感激有关如何正确执行此操作的任何指导或见解。
【问题讨论】:
标签: javascript reactjs redux react-jsx