【问题标题】:Javascript Saving and retrieving array data to and from localstorageJavascript 在本地存储中保存和检索数组数据
【发布时间】:2018-05-15 19:28:19
【问题描述】:

我有一个如下所示的数组:

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

我正在使用以下方法将其保存到本地存储:

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

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

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

这个问题是当我尝试获取数据时出现这个错误:

类型 NULL 不能分配给类型字符串。

我该如何解决这个问题?

【问题讨论】:

  • 适合我吗?
  • 您的代码没有显示 TypeScript 的迹象,但错误和标签表明您正在使用 TypeScript。你的 TypeScript 是什么样的(例如,你的类型注释是什么样的),你到底在哪一行得到了这个错误?即使猜测类型注释,我也看不到上面会产生该错误的行。 (一个不同的错误,但不是那个。)
  • 听起来像是编译错误,而不是别的什么。

标签: javascript typescript local-storage


【解决方案1】:

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

// 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 时才能看到此问题中的错误,因为这会捕获分配给string 的潜在null。

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

Argument of type 'string | null' is not assignable to parameter of type 'string'.
  Type 'null' is not assignable to type 'string'.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-29
    • 2019-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多