?由于業務的復雜,所以我們把相關UI抽離出來。但是數據變化了,沒法更新UI
@Builder
?MyGridLayout() {
? ?}
通過日志打印發現數據的確是更新了,但是UI就沒沒辦法,如何解決呢
@Entry
@Component
struct Page35 {// @State sArray: boolean[] = [false, false, false, false]@State dArray: boolean[][]= [[false, false], [false, false]]build() {Column() {ForEach(this.dArray,(item:[],index:number)=>{ForEach(item,(item_2:boolean,index_2:number)=>{Button('第'+index+'組,第'+index_2+'個,value:'+item_2).onClick(()=>{this.dArray[index][index_2] = !item_2//修改數據// 讓數組元素地址變更,從而觸發重繪// this.dArray[index] = [... this.dArray[index]]//方案一:拷貝數組// this.dArray[index] = JSON.parse(JSON.stringify(item))//方案二:序列化后再反序列化。//方案三:@Observed+@ObjectLink 參考官方文檔this.dArray.splice(index, 1, this.dArray[index]);//方案四:替換指定索引元素})})})}.width('100%')}
}
我這邊是通過方案四解決的,改變數據的時候,手動調用splice方法。