若干種在日常開發(fā)中會導致@Observed失效的情況
概述
@Observed與@ObjectLink是開發(fā)中常用的復雜數(shù)據(jù)類型綁定的技巧。
但是@Observed與@ObjectLink在開發(fā)中存在著許多坑。
接下來我將列舉我遇到的幾個坑。
測試環(huán)境
測試工具:DevEco Studio 3.1.1 Release
測試API版本號:API9
測試環(huán)境:
- OpenHarmony 3.2 Release
- HarmonyOS API9 模擬器
正確使用場景
首先我將舉例正確在開發(fā)中@Observed與@ObjectLink的正確使用方式,并且正確文件的源文件我也會打包放置在資源文件中。
先來看實現(xiàn)效果:
若干種在日常開發(fā)中會導致@Observed失效的情況-開源基礎軟件社區(qū)
源代碼:
若干種在日常開發(fā)中會導致@Observed失效的情況-開源基礎軟件社區(qū)
DataModel.ets:
// 接口
@Observed
export class DataInteface {
value: number;
}
// 實現(xiàn)數(shù)據(jù)類
@Observed
export class DataModel implements DataInteface {
value: number = 0;
}
Index.ets:
import { DataModel, DataInteface } from "../model/DataModel"
@Entry
@Component
struct Index {
@State
sensors: DataInteface[] = [
new DataModel(),
new DataModel(),
new DataModel(),
new DataModel(),
new DataModel(),
new DataModel(),
];
build() {
Row() {
List() {
ForEach(this.sensors, (item: DataInteface) => {
ListItem() {
SensorView({ sen: item })
}.width("100%")
})
}
.width("100%")
}
}
}
@Component
struct SensorView {
@ObjectLink
sen: DataInteface
build() {
Button(`點擊數(shù)據(jù)會自增${this.sen.value}`)
.fontSize(20)
.backgroundColor(Color.Yellow)
.onClick(() => {
this.sen.value++;
console.log("anran" + this.sen.value)
})
}
}
錯誤使用方法
1、使用interface撰寫接口
雖然按照TypeScript規(guī)范需要使用interface撰寫接口,但是@Observed不能修飾interface。所以在OpenHarmony開發(fā)中應當使用class撰寫接口。
效果:可以進行數(shù)據(jù)雙向綁定,但是編譯時會報錯。
錯誤代碼:
若干種在日常開發(fā)中會導致@Observed失效的情況-開源基礎軟件社區(qū)
// 接口
@Observed
export interface DataInteface {
value: number;
}
// 實現(xiàn)類
@Observed
export class DataModel implements DataInteface {
value: number = 0;
}
2、使用鏈式編程初始化數(shù)據(jù)
在OpenHarmony中不應當使用鏈式編程初始化@Observed修飾的對象。因為這將會替代掉@Observed幫助我們生產的對象轉而使用原生的數(shù)據(jù)對象。這將會導致所有的數(shù)據(jù)無法進行雙向綁定。
在實際項目中很容易因為一貫的編程經驗而使用鏈式編程,這時候就會出現(xiàn)問題,而且這種問題很難排查,小編就遇到了這種問題。
效果:
若干種在日常開發(fā)中會導致@Observed失效的情況-開源基礎軟件社區(qū)
代碼:
若干種在日常開發(fā)中會導致@Observed失效的情況-開源基礎軟件社區(qū)
3、直接使用for循環(huán)對@Observed對象渲染
直接使用for循環(huán)對@Observed對象渲染渲染,而不封裝,不使用@ObjectLink對數(shù)據(jù)引用。
運行效果:同錯誤2。
代碼:
若干種在日常開發(fā)中會導致@Observed失效的情況-開源基礎軟件社區(qū)
4、只給接口使用了@Observed沒有給實現(xiàn)類寫@Observed
運行效果:同錯誤2
代碼:
若干種在日常開發(fā)中會導致@Observed失效的情況-開源基礎軟件社區(qū)
5、沒有給接口使用@Observed,只給實現(xiàn)類寫@Observed
效果:程序可以正常雙向綁定,但是編譯器會給出警告。
代碼:
若干種在日常開發(fā)中會導致@Observed失效的情況-開源基礎軟件社區(qū)
結論
@Observed 可能是通過某種替代原有對象的方式實現(xiàn)的,所以使用鏈式編程初始化對象會導致數(shù)據(jù)雙向綁定失效。
而通常來說編譯器的警告都是自己編譯器給的,很可能不會正常影響程序運行。
@ObjectLink 與 @Observed 能夠極大的提高開發(fā)效率,但是也存在很多坑。特別是無法使用鏈式編程這種問題,會讓很多從其他開發(fā)方向轉OpenHarmony的老鳥都掉坑里。所以必須認真對待@ObjectLink 與 @Observed。
文章相關附件可以點擊下面的原文鏈接前往下載
https://ost.51cto.com/resource/2931