赞
踩
用简单的心境,对待复杂的人生,方能看淡得失,从容入世,潇洒自如,心变得简单了,世界也就简单了
目录
LocalStorage和AppStorage都是运行时的内存,但是在应用退出再次启动后,依然能保存选定的结果,是应用开发中十分常见的现象,这就需要用到PersistentStorage。
PersistentStorage是应用程序中的可选单例对象。此对象的作用是持久化存储选定的AppStorage属性,以确保这些属性在应用程序重新启动时的值与应用程序关闭时的值相同。
PersistentStorage将选定的AppStorage属性保留在设备磁盘上。应用程序通过API,以决定哪些AppStorage属性应借助PersistentStorage持久化。UI和业务逻辑不直接访问PersistentStorage中的属性,所有属性访问都是对AppStorage的访问,AppStorage中的更改会自动同步到PersistentStorage。
PersistentStorage和AppStorage中的属性建立双向同步。应用开发通常通过AppStorage访问PersistentStorage,另外还有一些接口可以用于管理持久化属性,但是业务逻辑始终是通过AppStorage获取和设置属性的。
PersistentStorage允许的类型和值有:
number, string, boolean, enum
等简单类型。JSON.stringify()
和JSON.parse()
重构的对象。例如Date, Map, Set
等内置类型则不支持,以及对象的属性方法不支持持久化。PersistentStorage不允许的类型和值有:
undefined
和 null
。持久化数据是一个相对缓慢的操作,应用程序应避免以下情况:
持久化大型数据集。
持久化经常变化的变量。
PersistentStorage的持久化变量最好是小于2kb的数据,不要大量的数据持久化,因为PersistentStorage写入磁盘的操作是同步的,大量的数据本地化读写会同步在UI线程中执行,影响UI渲染性能。如果开发者需要存储大量的数据,建议使用数据库api。
PersistentStorage和UIContext相关联,需要在UIContext明确的时候才可以调用,如果没有在UIContext明确的地方调用,将导致无法持久化数据。
父组件
- import ProvideTest from './ProvideTest';
-
- PersistentStorage.PersistProp('yuanzhen', 100);
-
- @Entry()
- @Component
- struct Index {
- @StorageLink("yuanzhen") yuanzhen:number =888
-
- build() {
- Column(){
- Text("父name:" + this.yuanzhen)
- .fontSize(50)
- .fontWeight(FontWeight.Bold)
- .onClick(() => {
- this.yuanzhen=999
- })
- ProvideTest()
- }
- }
- }
子组件
- @Component
- export default struct ProvideTest {
-
- @StorageLink("yuanzhen")yuanZhen:number =1000
-
- build() {
- Row() {
- Column() {
- Text("子name:"+this.yuanZhen)
- .fontSize(50)
- .fontWeight(FontWeight.Bold)
- .onClick(() => {
- this.yuanZhen=123456
- })
- }.width('100%')
- }.height('100%')
- }
- }
运行
点击父
点击子
新应用安装后首次启动运行:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。