-
Notifications
You must be signed in to change notification settings - Fork 1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: localStorage in Taro #4
Conversation
首先感谢 pr 👍 抹平差异可以算是 polyfill 要做的事情, 放在这里是对的. tarojsx/history 并没有实现浏览器的 History API, 当初在 taro rfcs 里讨论过发现小程序和路由功能和浏览器不兼容. 模拟 localStorage 挂载在 window 对象下, 用到 localStorage 的 npm 包就会尝试使用它, 这些第三方库默认 localStorage.getItem 返回字符串, 尝试对返回结果做解析 JSON.parse, 解析失败后假定数据损坏, 使用默认值替换. 如果 API 不一致, 可能会出现意想不到的结果. 从另一个角度讲, 用户在使用的时候, 也是希望和 web 端保持一致的, Typescript 在 dom.d.ts 里也是把 getItem 和 setItem 的值类型定义为 string 的. 所以我们要解决2个问题:
另外 localStorage[key] 这种方式涉及到 Proxy 太麻烦, 暂且不管吧. |
是不是用 可能会有一些 edge case,但考虑第三方库既然选择通过这个 api 去获取某个 key 对应的值,那么这个值应该是它自己存进去的,一般是不会出现这个值是非 |
src/bom/storage.ts
Outdated
*/ | ||
key(index: number): string | null { | ||
const { keys } = Taro.getStorageInfoSync() | ||
if (index >= keys.length) return null |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
index < 0 时也应该返回 null, 不加限制会返回 undefined.
确实是 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
非常感谢, 可以合并的时候告诉我一声, 或者去掉 WIP 标记.
现在还有 sessionStorage 和 StorageEvent 两个 API 没有补全。 sessionStorage 的实现方式和 localStorage 应该一样,唯一区别是它应该在小程序中的表现是关闭之后清除这次存储的所有数据。(因为小程序没有 StorageEvent 将依赖于 addEventListener。考虑是否可以用 |
sessionStorage 最简单的实现方式是使用 优点:
缺点:
另外容量无限, 即是优点也是缺点. |
src/bom/storage.ts
Outdated
} | ||
} | ||
|
||
export const localStorage = new Storage() |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
这里应该是 new TaroStorage()
StorageEvent 感觉可以先放一放, 先问一下 taro 那边对 window.addEventListener 的态度 |
OK。那这个 PR 就这样了。你再看看,没问题的话就合并吧~谢谢! |
🍻 合并, 然后我加上 e2e 测试. |
为 Taro 增加
Storage
polyfill。QUESTION
TODO
StorageEvent