Harmony NEXT-Difference between State Management V1 and State Management V2

xiaoxiao
2 min read

1.In V2, there is no @Link for bidirectional binding of parent and child components。

Therefore, we need to call the parent component's event through the @Event in the child component to implement the decoration callback (in the vernacular: the child component calls the function of the @Event decoration, passes in the parameters, and modifies the parameters in the parent component). In the parent component, pass in the function to the child component, note that we need to use the arrow function to wrap the function we write to the event, to ensure that the this of the event we pass in is not empty.
@Event can only be used in components that @ComponentV2 decoration
Sample code:

@Entry
@ComponentV2
struct Index {
  @Local title: string = "待修改";

  build() {
    Column() {
      Child({
        changeFactory: () => {
         this.title="已修改"
        }
      })
    }
  }
}


@ComponentV2
struct Child {
  @Event changeFactory: () => void = () => {};
  build() {
    Column() {
      Button("改变标题")
        .onClick(() => {
          this.changeFactory();
        })
    }
  }
}

2.The @State in V1 turned into @Local

@State decorator is not aware of initialization from the outside
The name has changed, but the writing is still the same, but @Local cannot be mixed with the @Observed decorated class instance object. Everything else is the same: For example, when decorating simple type arrays and value types, you can observe changes in the array as a whole or in the array items and changes in the value type.

3.@Watch is @Monitor in V2

In V1@Watch you can only listen to the changes in the first layer of attributes, while in V2, you can @Monitor and modify, and use @Trace in the corresponding deep variables.
Simple implementation of the sample code:

@Entry
@ComponentV2
struct monitorExample {
  @Local apple: number = 0;
  @Monitor('apple')
  onFruitChange(monitor: IMonitor) {
    console.log(`apple changed from ${monitor.value()?.before} to ${monitor.value()?.now}`);
  }


  build() {
    Column(){
      Text(`apple count: ${this.apple}`)
      Button("add apple")
        .onClick(()=> {
          this.apple++;
        })
    }
  }
}

0
Subscribe to my newsletter

Read articles from xiao directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

xiao
xiao