繁体   English   中英

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

[英]Storing array into localstorage in React

我有一个数组items [],其中我要输入4个键,其值来自输入框。

我现在在数组中有值,但是在页面刷新时,值已重置,所以我想为此使用localStorage-

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

为了找回它,我尝试了-

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

但这似乎不起作用,刷新后值仍然消失

新代码-

 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; 

localstorage设置值之前,需要检查条件。 喜欢,

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

因为刷新页面时。 加载函数可能会清除该数组,并将该空数组值再次设置到本地存储中。

编辑:

您可以通过使用全局标志变量IsNewData 当您提交新数据集IsNewData == true并在提交完成后执行IsNewData == false 还要在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