重新启动SwiftUI View生命周期

问题描述

我在View生命周期和快速的视图可重用性方面苦苦挣扎。

在此示例中,可以使用其他ID重新初始化我的视图,然后必须负责异步显示用户名。我以前在OnAppear内部运行loadData函数,但是在第一次加载后它不会重新初始化。但是,既然我添加了init函数,则在任何init上都不会完全更新我的状态和视图。

struct TestView: View {
    
    @State var userName : String  = ""
    
    init(id: Int){
        print("Init \(id)")
        loadData(id: id)
    }
    
    var body: some View {
        vstack{
            if userName != "" {
                Text(userName)
            }
        }
    }
    
    // function that will return username at some point in the future
    private func loadData(id: Int){
        let Obs: Observable<String> = manager.getUser(id: id)
               
       Obs.subscribe(onNext: { user in
            self.userName = user.userName
       })
    }
}

解决方法

视图无法重建,因为在提供的变体中它被解释为相等的(因为没有存储任何不同的属性)

尝试以下

struct TestView: View {
    let id: Int            // << changing this should make view rebuild
    @State private var userName : String  = ""
    
    var body: some View {
        VStack{
            if userName != "" {
                Text(userName)
            }
        }
        .onAppear {
            print("Rebuild with: \(id)")
            loadData(id: id)
        }
        .id(self.id)     // << Update: this one !!
    }
    
    // function that will return username at some point in the future
    private func loadData(id: Int){
        let Obs: Observable<String> = manager.getUser(id: id)
               
       Obs.subscribe(onNext: { user in
            self.userName = user.userName
       })
    }
}