Javascript从localstorage中保存和检索数组数据

时间:2017-12-01 16:37:15

标签: javascript typescript local-storage

我有一个看起来像这样的数组:

this.data = [
    { cols: 1, rows: 1, y: 0, x: 4 },
    { cols: 1, rows: 1, y: 2, x: 5 }
];

我使用以下方法将其保存到localstorage:

localStorage.setItem('my_data', JSON.stringify(this.data));

然后我使用以下方法检索它:

this.data = JSON.parse( localStorage.getItem('my_data'));

这个问题是,当我尝试获取数据时,我收到此错误:

  

类型NULL不能分配给Type String。

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

要删除类型错误(仅在严格的东西启用时显示),您可以确保处理空值:

// Warning... don't use this code until you read the next section!
data = JSON.parse(localStorage.getItem('my_data') || '');

这是因为localStorage.getItem可以返回string | null,但JSON.parse只接受string(即非空)。

正确代码

如果您还希望您的代码能够得到合理的工作,我建议的解决方案将更进一步,并提供合理的默认JSON字符串:

data = JSON.parse(localStorage.getItem('my_data') || '[]');

错误注释

此问题中的错误只有在启用strictNullChecks时才会显示,因为这会捕获分配给null的潜在string

这种情况下的确切错误是:

Argument of type 'string | null' is not assignable to parameter of type 'string'.
  Type 'null' is not assignable to type 'string'.
相关问题