Redux更改深度嵌套数组的值

时间:2020-06-02 13:23:04

标签: javascript reactjs redux

我的初始状态如下:

const initState = {
    posts: data
}

现在发布的内容类似于:

[
  {
    "id": "",
    "text": "",
    "slug": "",
    "title": "",
    "comments": []
  },

//some more here
]

所以我想做的是,当调度被触发时,我想向该特定注释数组添加新注释。这是我的方法:

 if (action.type === "ADD_COMMENT") {
        let findPost = state.posts.find(post => post.slug === action.payload.comment.postSlug);
        let index = state.posts.indexOf(findPost);
        console.log(findPost);

        return {
            ...state,
            posts: [...state.posts,
            state.posts[index].comments = [action.payload.comment, ...state.posts[index].comments]]
        }
    }

即使我的应用程序运行正常,但redux状态仍然存在问题。因为每次都发生动作,它会将新注释添加到该特定数组中,并将新数组置入状态。

因此,在触发新动作的情况下,我确实得到了以下信息:

[
  {
    "id": "",
    "text": "",
    "slug": "",
    "title": "",
    "comments": ["comment here"]
  },
[
  {
    "comments": ["comment here"]
  },

//some more here
]

]

每次单击都会在我的状态下创建一个我完全不需要的新条目。我如何才能使它仅将注释添加到该特定数组中,而不能作为单独的条目添加

2 个答案:

答案 0 :(得分:2)

您将新评论推送到“帖子”数组中,而不是帖子的对象中。

您可以尝试地图

if (action.type === "ADD_COMMENT") {

 const posts = state.posts.map(post => {
       if( post.slug === action.payload.comment.postSlug){
          post.comments.unshift(action.payload.comment);
       }
       return post
    });

    return {...state, posts}
}

编辑:使用此解决方案,您可以改变状态,不建议使用 为避免这种情况,只需将您的帖子复制到一个新变量中

let posts = [...state.posts]

然后绘制地图。

答案 1 :(得分:2)

在有效负载中传递注释数组的索引。

if (action.type === 'ADD_COMMENT') {
  // get the index of the item from the payload
  const index = action.payload.index;
  // create a copy
  const posts = [...state.posts];
  // add comment to comments array
  posts[index].comments.push(action.payload.comment);

  console.log(posts[index]);

  return {
    ...state,
    posts: posts,
  };
}