简体   繁体   English

Dexie.js 查询 with.equals 不适用于 localStorage

[英]Dexie.js query with .equals not working with localStorage

I am trying get a value from indexedDB with Dexie.js but it does not recognize the value from localStorage.我正在尝试使用 Dexie.js 从 indexedDB 获取值,但它无法识别来自 localStorage 的值。

I tried async/await, promises, placing localstorage call on created, mounted, outside export default, and none of these ways worked.我尝试了 async/await、promise、将 localstorage 调用放在已创建、已安装、外部导出默认值上,但这些方法都不起作用。

fetchData() {
  return dbDexie.tactics1
    .where('i')
    .equals(localStorage.getItem("id")) // Here is the problem
    .toArray()
    .then((r) => r[0].f);
}

.equals strict equality .equals严格相等

The equals method is a strict equality test, so if id is a number type in indexedDB , then the string type returned from localStorage won't match, because of the different types. equals方法是一个严格的相等测试,所以如果idindexedDB中的数字类型,那么从localStorage返回的字符串类型将不匹配,因为类型不同。 And localStorage only stores strings.localStorage只存储字符串。

For this reason, it's common to see JSON.parse used when retrieving data from localStorage , to convert serialized data:出于这个原因,在从localStorage检索数据时,通常会看到JSON.parse用于转换序列化数据:

fetchData() {
  return dbDexie.tactics1
    .where('i')
    .equals(JSON.parse(localStorage.getItem("id")))
    .toArray()
    .then((r) => r[0].f);
},

Or you could more explicitly cast the localStorage value to a Number type:或者您可以更明确地将localStorage值转换为 Number 类型:

.equals(Number(localStorage.getItem("id")))

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

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