Reactjs 具有多个键值对的本地存储
我正在使用react创建一个注释部分,因为我需要将所有输入文本存储到本地存储器中。 但我面临的问题是,每当我在评论部分写下另一条评论时,我的本地存储就会被重新加载Reactjs 具有多个键值对的本地存储,reactjs,Reactjs,我正在使用react创建一个注释部分,因为我需要将所有输入文本存储到本地存储器中。 但我面临的问题是,每当我在评论部分写下另一条评论时,我的本地存储就会被重新加载 如何将唯一的键值添加到本地存储?首先,我建议您将注释存储在数组中,然后将其存储在本地存储中 做这样的事- const AddComments = () => { let commentsArray = localStorage.getItem("Comments") // Get Previous C
如何将唯一的键值添加到本地存储?首先,我建议您将
注释
存储在数组
中,然后将其存储在本地存储
中
做这样的事-
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
}
你是说你有这样的东西:
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(注释)
然后添加到parsedComments数组并将其放回本地存储。无论您是否使用数组或不同的数据结构来保存注释,都应该是相同的。如果你需要在应用程序的多个部分访问文章、评论等,你也可以考虑使用。你能共享一些代码吗?你的PROB需要<代码> JSON.PARSER()< <代码> >