gpt4 book ai didi

swift - 如果有条件,@ObservedObject 不会触发重绘

转载 作者:行者123 更新时间:2023-12-05 06:58:52 24 4
gpt4 key购买 nike

我有以下代码:

import SwiftUI

struct RootView: View {
@ObservedObject var authentication: AuthenticationModel

var body: some View {
ZStack {
if self.authentication.loading {
Text("Loading")
} else if self.authentication.userId == nil {
SignInView()
} else {
ContentView()
}
}
}
}

但是,@ObservedObject 的更改似乎不会触发切换到其他 View 。我可以通过渲染“修复”这个问题

    var body: some View {
VStack {
Text("\(self.authentication.loading ? "true" : "false") \(self.authentication.userId ?? "0")")
}.font(.largeTitle)
ZStack {
if self.authentication.loading {
Text("Loading")
} else if self.authentication.userId == nil {
SignInView()
} else {
ContentView()
}
}
}

突然它开始工作了。如果监视的属性仅在条件中使用,为什么 @ObservedObject 似乎不会触发重新呈现?

AuthenticationModel 的代码是:

import SwiftUI
import Combine
import Firebase
import FirebaseAuth

class AuthenticationModel: ObservableObject {
@Published var userId: String?
@Published var loading = true

init() {
// TODO: Properly clean up this handle.
Auth.auth().addStateDidChangeListener { [unowned self] (auth, user) in
self.userId = user?.uid
self.loading = false
}
}
}

最佳答案

我认为问题可能在于您没有创建 AuthenticationModel 的实例。您可以在 RootView 中尝试以下操作吗?:

@ObservedObject var authentication = AuthenticationModel()

关于swift - 如果有条件,@ObservedObject 不会触发重绘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64518852/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com