微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

重新启动SwiftUI View生命周期

如何解决重新启动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
       })
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。