简体   繁体   English

在React中将数组存储到本地存储

[英]Storing array into localstorage in React

I have an array items[] in which I am inputting 4 keys with values coming from input box. 我有一个数组items [],其中我要输入4个键,其值来自输入框。

I now have the values in the array but on page refresh the values are reset, So I was thinking of using localStorage for this i tried - 我现在在数组中有值,但是在页面刷新时,值已重置,所以我想为此使用localStorage-

  localStorage.setItem("test", JSON.stringify(items)); 

and for retrieving it i tried - 为了找回它,我尝试了-

 var retrievedData = localStorage.getItem("test"); var test2 = JSON.parse(retrievedData); 

But this doesn't seem to be working, the values are still disappearing after refresh 但这似乎不起作用,刷新后值仍然消失

new code- 新代码-

 import React, { Component } from 'react'; import { Table } from 'reactstrap'; class Tab extends React.Component { render() { const items = this.props.items; items.sort((a,b) => { const name1 = a.name.toLowerCase(), name2 = b.name.toLowerCase(); return name1 === name2 ? 0 : name1 < name2 ? -1 : 1; }); localStorage.setItem("test", JSON.stringify(items)); var retrievedData = localStorage.getItem("test"); var test2 = JSON.parse(retrievedData); return ( <Table striped> <thead> <tr> <th >Name</th> <th>Origin</th> <th>Destination</th> <th>Seats</th> </tr> </thead> <tbody> {test2.map(item => { return ( <tr> <td>{item.name}</td> <td>{item.origin}</td> <td>{item.destination}</td> <td>{item.seats}</td> </tr> ); })} </tbody> </Table> ); } } export default Tab; 

You need to check a condition before set the values in localstorage . localstorage设置值之前,需要检查条件。 like, 喜欢,

if(localStorage.getItem("test") === undefined)
{
localStorage.setItem("test", JSON.stringify(items));
}

Because when you refresh your page. 因为刷新页面时。 on load function may clear the array and set that empty array values into the local storage again. 加载函数可能会清除该数组,并将该空数组值再次设置到本地存储中。

Edit: 编辑:

You can do it by using a global flag variable as IsNewData . 您可以通过使用全局标志变量IsNewData When you submit new data set IsNewData == true and do IsNewData == false after completion of submitting. 当您提交新数据集IsNewData == true并在提交完成后执行IsNewData == false Also add the additional condition in the if statement :) 还要在if语句中添加其他条件:)

if(localStorage.getItem("test") === undefined ||  IsNewData)
{
localStorage.setItem("test", JSON.stringify(items));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM