我正在研究 React JS 中的嵌套注释功能。 我无法删除嵌套评论。基本上每个评论都有一个属性回复,它是对象数组(与父评论对象完全相同)。
当我尝试使用复制和修改的对象数组更新内部循环(updateCommentsData(parentStateCopy);)中的父状态时,它会抛出此错误: updateCommentsData 不是一个函数,即使修改后的对象数组在控制台记录它时似乎是正确的。
删除功能:
function deleteComment(id) {
for (let i = 0; i < commentsData.length; i++) {
if (commentsData[i].id === id) {
updateCommentsData((prev) => {
return prev.filter((item) => item.id !== id);
});
break;
} else {
if (commentsData[i].replies.length !== 0) {
for (let j = 0; j < commentsData[i].replies.length; j++) {
repliesStateCopy.push(commentsData[i].replies[j]);
if (commentsData[i].replies[j].id === id) {
repliesStateCopy = repliesStateCopy.filter(
(item) => item.id !== id
);
parentStateCopy[i].replies = repliesStateCopy;
updateCommentsData(parentStateCopy);
break;
}
}
}
}
}
JSON 数据看起来像这样:
"comments": [
{
"id": 1,
"content": "Impressive! Though it seems the drag feature could be improved. But overall it looks incredible. You've nailed the design and the responsiveness at various breakpoints works really well.",
"createdAt": "1 month ago",
"score": 12,
"user": {
"image": {
"png": "./images/avatars/image-amyrobson.png",
"webp": "./images/avatars/image-amyrobson.webp"
},
"username": "amyrobson"
},
"replies": []
},
{
"id": 2,
"content": "Woah, your project looks awesome! How long have you been coding for? I'm still new, but think I want to dive into React as well soon. Perhaps you can give me an insight on where I can learn React? Thanks!",
"createdAt": "2 weeks ago",
"score": 5,
"user": {
"image": {
"png": "./images/avatars/image-maxblagun.png",
"webp": "./images/avatars/image-maxblagun.webp"
},
"username": "maxblagun"
},
"replies": [
{
"id": 3,
"content": "If you're still new, I'd recommend focusing on the fundamentals of HTML, CSS, and JS before considering React. It's very tempting to jump ahead but lay a solid foundation first.",
"createdAt": "1 week ago",
"score": 4,
"replyingTo": "maxblagun",
"user": {
"image": {
"png": "./images/avatars/image-ramsesmiron.png",
"webp": "./images/avatars/image-ramsesmiron.webp"
},
"username": "ramsesmiron"
},
"replies": []
},
{
"id": 4,
"content": "I couldn't agree more with this. Everything moves so fast and it always seems like everyone knows the newest library/framework. But the fundamentals are what stay constant.",
"createdAt": "2 days ago",
"score": 2,
"replyingTo": "ramsesmiron",
"user": {
"image": {
"png": "./images/avatars/image-juliusomo.png",
"webp": "./images/avatars/image-juliusomo.webp"
},
"username": "juliusomo"
},
"replies": []
}
]
},
我认为问题是 updateCommentsData 是直接使用 ParentStateCopy 调用的,而不是使用状态设置器函数的回调模式(prev => newState)。
试试这个代码:
const deleteComment = (commentId) => {
setComments(prevComments => {
const deleteRecursively = (comments) => {
return comments.reduce((acc, comment) => {
if (comment.id === commentId) return acc;
return [...acc, {
...comment,
replies: deleteRecursively(comment.replies)
}];
}, []);
};
return deleteRecursively(prevComments);
});
};