React JS Redux如何更新状态



我在还原器中有一个redux态,如下所示:帖子:

[0] post_id:1010
    post_title:"Title1" 
    post_comments [0] id=1 Title="Some text0"
                  [1] id=2 Title="Some text1"
[1] post_id:1011
    post_title:"Title2" 
    post_comments: [0] id=11 Title="Some text Comments0"
                   [1] id=22 Title="Some text Comments1"

当用户插入新的帖子注释时,如果我的响应为id = 33 title =" loreim ispum",我该如何添加到发表注释。我需要将其添加到post_id:1011中,我也有回应。我目前在reducer中尝试过:

   items = state.posts;
   items[key].comments =  items[key].comments.concat(action.data);
   return Object.assign({}, state, {
        asyncLoading: true,
        asyncError: null,
        posts:items
    });

预先感谢

您可以使用传播操作员并更新

return {
    ...state,
       asyncLoading: true,
       asyncError: null,
       posts: {
           ...state.posts.slice(0, post_index),
           {
                ...state.posts[post_index],
                post_comments: [...state.posts[post_index].post_comments, action.payload]
           },
           ...state.posts.slice(post_index 
+ 1),
       }
   }

相关内容

  • 没有找到相关文章

最新更新