如何维护引用以更新嵌套数组/字典(javascript)?



我正在努力创建一个评论线程,它将评论添加到适当的嵌套位置。下面是一个示例评论线程(一个主要评论,有 3 个直接回复 [来自 Bob、James、Allan],其中 2 个直接回复有自己的直接回复 [来自 John, Levy]):

[{
username: "Kevin",
date: "3 hours ago",
text: "#Hellon>quotenn",
votes: 12,
comments: [
{
username: "Bob",
date: "2 hours ago",
text: "^ click the minimize button to hide threads",
votes: 8,
comments: [
{
username: "John",
date: "1 hours ago",
text: "<- Click the arrows to vote",
votes: 3,
comments: [],
},
],
},
{
username: "James",
date: "4 hours ago",
text: "click on reply to open up a text prompt",
votes: 5,
comments: [],
},
{
username: "Allan",
date: "10 mins ago",
text: "this",
votes: 2,
comments: [
{
username: "Levy",
date: "8 mins ago",
text: "is",
votes: 1,
comments: [],
},
],
},
],
},
],
},
],
},
]

我正在一个组件中工作,其中此字典作为prop(prop.comments)传递,并且可以更新此字典的setComments(react useState)函数也是如此。我也可以访问特定评论的路径。我希望能够为我拥有的路径的评论添加评论。例如,路径可能类似于 [0, 1]。这意味着转到索引 0 处的评论(凯文的),然后转到索引 1 处的评论("詹姆斯")。然后我要补充詹姆斯的评论。

问题是我不知道如何更新特定的嵌套注释,然后使用 setComment(useState 函数)实际更新原始数据库。这是我尝试过的,但它无法更新原始数组。

props.comments:整个数组(如上所示)

props.setComments:更新此原始数组的方法

props.path:特定注释的路径(即 [0,1])

onClick={() => {
let temp = [...props.comments];
let originalData = [...temp];
props.path.map((index, i) => {
if (originalData) {
originalData = [...originalData[index].comments];
}
if (i == props.path.length - 1) {
let newArray = [...originalData];
newArray.push({
username: "Kevin",
date: "now",
text: "JASDFASDF",
votes: 0,
comments: [],
});
originalData = newArray;
}
});
props.setComments(temp);
}}

如果我是你,我会改变评论数组的工作方式。目前,您的注释对象如下所示:

interface Comment {
username: string;
date: Date;
text: string;
votes: number;
comments: Comment[];
}

您当前遇到的问题是嵌套注释。 要避免此问题,您可以将注释对象更改为如下所示:

interface Comment {
id: string;
replyTo: string | null;
username: string;
date: Date;
text: string;
votes: number;
}

在这里,我们删除了注释数组,并将其替换为当前注释的idreplyTo,这将是此注释回复的评论的id。如果它没有回复任何内容,那么它将为空。

现在我们将没有嵌套,因此您可以轻松循环并添加注释。此外,数组应该更易于使用。

最新更新