后代组件通过 @Consume 订阅这个 @State 变量。当异步数据到达并更新 @State 时,@Consume 的组件会自动收到更新并重新渲染,显示最终的数据。这种方式将异步操作的管理和状态管理结合起来,符合响应式原则。@Entry @Component struct AsyncProvideExample { // Provide 用来存储异步结果的状态 @Provide @State fetchedData: string | null = null; async aboutToAppear() { // 模拟异步获取数据 this.fetchDataAsync(); } async fetchDataAsync() { try { // 模拟网络延迟 await new Promise(resolve => setTimeout(resolve, 1500)); const data = "Data fetched successfully!"; // 更新状态变量 this.fetchedData = data; } catch (error) { this.fetchedData = "Error fetching data"; } } build() { Column({ space: 10 }) { Text("Ancestor Component") if (this.fetchedData === null) { LoadingProgress().width(50) } else { Text(`Ancestor sees: ${this.fetchedData}`) } AsyncConsumeChild() } } } @Component struct AsyncConsumeChild { // Consume 存储异步结果的状态 @Consume fetchedData: string | null; build() { Column() { Text("Descendant Component").margin({ top: 20 }) if (this.fetchedData === null) { Text("Loading data...") } else { Text(`Descendant consumes: ${this.fetchedData}`) } } } }
后代组件通过 @Consume 订阅这个 @State 变量。当异步数据到达并更新 @State 时,@Consume 的组件会自动收到更新并重新渲染,显示最终的数据。这种方式将异步操作的管理和状态管理结合起来,符合响应式原则。