DEV Community

xiaoyao-yao
xiaoyao-yao

Posted on • Edited on

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

  1. In V2, there is no @link to bind parent and child components in both directions. Therefore, we need to @Event the events of the parent component 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 = "To be modified";

build() {
Column() {
Child({
changeFactory: () => {
this.title="Revised"
}
})
}
}
}

@ComponentV2
struct Child {
@Event changeFactory: () => void = () => {};
build() {
Column() {
Button("Change the title")
.onClick(() => {
this.changeFactory();
})
}
}
}

  1. The @State in V1 has been transformed 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++;
})
}
}
}

Extend:

V1: Relies on decorator chains (such as @State @ObjectLink) to implement one-way data flow, and only supports the observation of the first-layer properties of objects. Nested objects need to encapsulate components layer by layer, and the code is redundant.

V2: Implements deep attribute monitoring through @ObservedV2 @trace, and supports attribute change detection (such as obj.a.b.c) of nested objects at any level, without the need for additional component encapsulation

Top comments (0)