具有多个键值对的本地存储

时间:2021-04-30 06:51:47

标签: reactjs

我正在使用 react 创建一个评论部分,因为我需要将所有输入文本存储到本地存储中。 但我面临的问题是,每当我在评论部分写另一条评论时,我的本地存储都会重新加载。

如何将唯一键值添加到本地存储中???

2 个答案:

答案 0 :(得分:0)

首先,我建议您将 Comments 存储在 array 中,然后将其存储在 localStorage 中。

做这样的事情 -

const AddComments = () => {
    let commentsArray = localStorage.getItem("Comments") // Get Previous Comments
    let temp = []

    if(commentsArray !== null) {
        temp = [...JSON.parse(commentsArray)]
    }

    temp.push({
        comment: "New Comment",
        _id: "id of new comment",
    })
    localStorage.setItem("Comments", JSON.stringify(temp)) // This will add new comment to previous comment
}

答案 1 :(得分:0)

你的意思是你有这样的东西:

const comments = [];
// some form to create a comment storing it in a var comment
comments.push(comment);
const commentsJsonified = JSON.stringify(comments);
localStorage.setItem('comments', commentsJsonified);

如果是这样,那么您可以使用

从本地存储中获取评论

const comments = localStorage.getItem('comments')

解析它们

const parsedComments = JSON.parse(comments)

然后添加到 parsedComments 数组并将其放回本地存储。无论您是使用数组还是不同的数据结构来保存注释,它都应该是相同的。如果您需要访问应用多个部分中的帖子、评论等,您也可以考虑使用 Redux-Persist