如何正确处理双嵌套数组中的状态(ReactJS + Redux)?

时间:2016-06-29 17:00:20

标签: javascript reactjs redux react-jsx

我正在尝试构建以下内容:一个可以创建帖子的论坛,该帖子会触发ADD_POST,并创建帖子,并添加到帖子'对象数组。每个帖子'对象初始化为'评论'将在该帖子中输入的评论文本(' 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')到帖子中。评论'数组

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

我不建议直接改变状态,所以我很感激任何有关如何正确执行此操作的指导或见解。

2 个答案:

答案 0 :(得分:1)

您可以考虑规范化数据。所以,不要像这样存储你的结构:

posts: [{
  title: 'Some post',
  comments: [{
    text: 'Hey there'
  }]
}]

你会像这样存储它们:

posts: [{
  id: 1,
  title: 'Some post'
}]

comments: [{
  id: 4,
  postId: 1,
  text: 'Hey there'
}]

起初它更像是一种痛苦,但却具有很大的灵活性。

或者,您可以修改ADD_COMMENT减速器:

return posts.map(function(post) { 
  if (post.id !== action.id) {
    return post
  }


  return {
    ...post, 
    comments: [
      ...post.comments, 
      { 
        id: action.id, 
        commentTxt: action.commentTxt 
      }
    ]
  }
}

注意:在最后一个解决方案中,没有突变。不知道大量评论会如何表现,但除非你有充分的理由,否则我不会对这种情况进行预优化。

答案 1 :(得分:1)

正如克里斯托弗戴维斯在答案中所说,你应该规范你的国家。假设我们有这样的形状:

const exampleState = {
    posts: {
        '123': {
            id: '123',
            title: 'My first post',
            comments: []  // an array of comments ids
        },
        '456': {
            id: '456',
            title: 'My second post',
            comments: []  // an array of comments ids
        }
    },
    comments: {
        'abc': {
            id: 'abc',
            text: 'Lorem ipsum'
        },
        'def': {
            id: 'def',
            text: 'Dolor sit'
        },
        'ghi': {
            id: 'ghi',
            text: 'Amet conseguir'
        }
    }
}

好的,现在让我们写一些动作创建者来创建会改变状态的动作:

const addPost = (post) => ({
    type: 'ADD_POST',
    post
})

const addComment = (postId, comment) => ({  // for the sake of example, let's say the "comment" object here is a comment object returned by some ajax request and having it's own id
    type: 'ADD_COMMENT',
    postId,
    comment
})

然后,您将需要两个Reducer来处理posts slice,并且注释切片:

const postsReducer = (posts = {}, action = {}) => {
    switch(action.type) {
        case 'ADD_POST':
            const id = getId(posts)
            return {
                ...posts,
                [id]: action.post
            }
        case 'ADD_COMMENT':
            return {
                ...posts.map(p => {
                    if (p.id == action.postId) {
                        return {
                            ...p,
                            comments: p.comments.concat([action.comment.id])
                        }
                    }
                    return p
                })
            }
        default:
            return state
    }
}

const commentsReducer = (comments = {}, action = {}) => {
    switch(action.type) {
        case 'ADD_COMMENT':
            return {
                ...comments,
                [action.comment.id]: action.comment
            }
        default:
            return state
    }
}

让我们创建一些选择器来从状态中获取数据:

const getPost = (state, id) => state.posts[id]

const getCommentsForPost = (state, id) => ({
    const commentsIds = state.posts[id].comments
    return state.comments.filter(c => commentsIds.includes(c.id))
})

然后,你的组件:

const PostLists = (posts) => (
    <ul>
        {posts.map(p) => <Post key={p} id={p} />}
    </ul>
)

PostLists.propTypes = {
    posts: React.PropTypes.arrayOf(React.PropTypes.string)  //just an id of posts
}


const Post = ({id, title, comments}) => (
    <li>
        {title}
        {comments.map(c) => <Comment key={c.id} {...c}/>}
    </li>
)

Post.propTypes = {
    id: React.PropTypes.string,
    comments: React.PropTypes.arrayOf(React.PropTypes.shape({
        id: React.PropTypes.string,
        text: React.PropTypes.text
    }))
}


const Comment = ({ id, text }) => (
    <p>{text}</p>
)

现在,连接的容器:

// the mapStateToProps if very simple here, we just extract posts ids from state
const ConnectedPostLists = connect(
    (state) => ({
        posts: Objects.keys(state.posts)
    })
)(PostLists)


// The ConnectedPost could be written naively using the component props passed as the second argument of mapStateToProps :
const ConnectedPost = connect(
    (state, { id }) => ({
        id,
        title: getPost(state, id).title,
        comments: getCommentsForPost(state, id)
    })
)(Post)

这样可行但是如果你有很多帖子,你会遇到ConnectedPost组件的性能问题,因为依赖于组件自己的道具的mapStateToProps http://www.stickpeople.com/projects/python/win-psycopg/ < / p>

所以我们应该像这样重写它:

// Since the post id is never intended to change for this particular post, we can write the ConnectedPost like this :
const ConnectedPost = connect(
    (_, { id}) => (state) => ({
        id,
        title: getPost(state, id).title,
        comments: getCommentsForPost(state, id)
    })
)

瞧!我没有测试这个例子,但我认为它可以帮助你看看你需要去哪个方向。