本文转载自《#2023 盲盒+码 # OpenHarmony 利用 ArkUI 状态治理开发范例》,作者:zhushangyuan_

本文依据橘子购物利用,实现 ArkUI 中的状态治理。

在申明式 UI 编程框架中,UI 是程序状态的运行后果,用户构建了一个 UI 模型,其中利用的运行时的状态是参数。当参数扭转时,UI 作为返回后果,也将进行对应的扭转。这些运行时的状态变动所带来的 UI 的从新渲染,在 ArkUI 中统称为状态管理机制。

自定义组件领有变量,变量必须被装璜器装璜才能够成为状态变量,状态变量的扭转会引起 UI 的渲染刷新。如果不应用状态变量,UI 只能在初始化时渲染,后续将不会再刷新。 下图展现了 State 和 View(UI)之间的关系。

治理组件领有的状态
@State 装璜器:组件内状态
@State 装璜的变量,或称为状态变量,一旦变量领有了状态属性,就和自定义组件的渲染绑定起来。当状态扭转时,UI 会产生对应的渲染扭转。

在状态变量相干装璜器中,@State 是最根底的,使变量领有状态属性的装璜器,它也是大部分状态变量的数据源。

@link 装璜器:父子双向同步
子组件中被 @Link 装璜的变量与其父组件中对应的数据源建设双向数据绑定。
@Link 装璜的变量与其父组件中的数据源共享雷同的值。

@Componentexport struct DetailPage {  @State currentLocation: string = ''}

在父组件 DetailPage 中申明以后定位 currentLocation 变量

Panel(this.isPanel) {    Location({ isPanel: $isPanel, currentLocation: $currentLocation })}

将 currentLocation 变量传给子组件 Location

@Componentexport struct Location {  @Link currentLocation: string}

子组件用 @Link 装璜的 currentLocation 接管。

  @Builder cityList(city: any) {    if (this.currentLocation === city.name) {      List() {        ForEach(city.city, twoCity => {          ListItem() {            Column() {              Text(`${twoCity}`)                .width('100%')                .height(30)                .fontSize(14)                .onClick(() => {                  this.currentLocation = city.name + '/' + twoCity                })            }          }        })      }      .width('100%')      .divider({ strokeWidth: 2, color: $r('app.color.divider'), startMargin: 0, endMargin: 20 })    }  }

子组件中的 currentLocation 变量扭转会同步父组件中的 currentLocation。

治理利用领有的状态
AppStorage 是利用全局的 UI 状态存储,是和利用的过程绑定的,由 UI 框架在应用程序启动时创立,为应用程序 UI 状态属性提供地方存储。

和 LocalStorage 不同的是,LocalStorage 是页面级的,通常利用于页面内的数据共享。而对于 AppStorage,是利用级的全局状态共享。AppStorage 应用场景和相干的装璜器:@StorageProp 和 @StorageLink

@StorageProp
@StorageProp(key)是和 AppStorage 中 key 对应的属性建设单向数据同步,咱们容许本地扭转的产生,然而对于 @StorageProp,本地的批改永远不会同步回 AppStorage 中,相同,如果 AppStorage 给定 key 的属性产生扭转,扭转会被同步给 @StorageProp,并笼罩掉本地的批改。

@Entry@Componentstruct HomePage {  @State curBp: string = 'md' // curBp指以后窗口断点,sm代表小屏,md代表中屏,lg代表大屏}

在Home.ets页面中,用 @State 申明以后窗口类型:curBp 变量并赋初值为 md,代表中屏。

  isBreakpointSM = (mediaQueryResult) => {    if (mediaQueryResult.matches) {      this.curBp = 'sm'      AppStorage.SetOrCreate('curBp', this.curBp)    }  }  isBreakpointMD = (mediaQueryResult) => {    if (mediaQueryResult.matches) {      this.curBp = 'md'      AppStorage.SetOrCreate('curBp', this.curBp)    }  }  isBreakpointLG = (mediaQueryResult) => {    if (mediaQueryResult.matches) {      this.curBp = 'lg'      AppStorage.SetOrCreate('curBp', this.curBp)    }  }

依据屏幕尺寸,将 curBp 设置为相应的值,并用 SetOrCreate()办法保留在 AppStorage 中。

在子组件 NavigationHomePage 中间接应用 curBp 变量

@Entry@Componentexport struct NavigationHomePage {  @StorageProp('curBp') curBp: string = 'sm'}

curBp 是依据窗口的尺寸判断的,是不能扭转的,因而应用 @StorageProp(‘curBp’)与 AppStorage(‘curBp’)建设单向数据同步。

@StorageLink
@StorageLink(key)是和 AppStorage 中 key 对应的属性建设双向数据同步:
1.  本地批改产生,该批改会被同步回 AppStorage 中;
2.  AppStorage 中的批改产生后,该批改会被同步到所有绑定 AppStorage 对应 key 的属性上,包含单向(@StorageProp 和通过 Prop 创立的单向绑定变量)、双向(@StorageLink 和通过 Link 创立的双向绑定变量)变量和其余实例(比方 PersistentStorage)。

@Entry@Componentstruct HomePage {  @StorageLink('shoppingCartGoodsList') shoppingCartGoodsList: { data: { id: number } }[] = []}

在Home.ets页面中,用 @StorageLink 装璜器定义 shoppingCartGoodsList,用于获取全局的购物车商品列表。

this.emitterClass.setShoppingCartGoodsList((eventData)=>{    this.shoppingCartGoodsList.push(eventData.data.id)    AppStorage.SetOrCreate('shoppingCartGoodsList', this.shoppingCartGoodsList)})

应用 AppStorage.SetOrCreate(‘shoppingCartGoodsList’, this.shoppingCartGoodsList)将购物车商品列表保留在 AppStorage 中。

因为购物车中的商品会联动的变动,比方在商品的详情页将商品增加至购物车,在首页也须要更新购物车信息,因而购物车商品列表采纳 @StorageLink 装璜器装璜,与 AppStorage(‘shoppingCartGoodsList’)建设双向同步。

运行测试成果
执行以下命令,能够下载橘子购物利用工程:

git initgit config core.sparsecheckout trueecho code/Solutions/Shopping/OrangeShopping/ > .git/info/sparse-checkoutgit remote add origin https://gitee.com/openharmony/applications_app_samples.gitgit pull origin master

参考资料
橘子购物示例利用