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;
}