由于业务的复杂,所以我们把相关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方法。