My Redux狀態存儲一個存儲註釋數組的對象comments
。每個comment
對象都有一個replies
數組。我將父註釋ID和回覆ID都傳遞給我的reducer,意圖從回覆數組中刪除回覆。Redux - 從嵌套在另一個陣列中的陣列中刪除對象
我的頂級評論對象的簡化版本是這樣的:
{
"count": 4,
"data": [
{
id: 123,
text: 'This is a comment',
replies: [
{
id: 479,
text: 'This is a reply',
},
{
id: 293,
text: 'This is another reply',
},
],
},
{
id: 728,
text: 'This is another comment',
replies: [
{
id: 986,
text: 'This is a reply',
},
],
},
],
"pageSize": 5,
cursor: "",
}
這裏是我的減速器出現包裹父評論對象的數組和扁平的答覆(顯然不是期望結果,但我對處理嵌套數組的最佳方式感到不知所措)。
case types.DELETE_REPLY_SUCCESS: {
const content = Object.assign({}, state);
content.data = content.data.map((comment) => {
const newObj = { ...comment };
if (newObj.id === action.parentCommentId) {
return newObj.replies.filter(reply => reply.id !== action.replyId);
}
return newObj;
});
return content;
}