0

我收到错误

致命错误:未找到 LoginResponse 类型的 ObservableObject。LoginResponse 的 View.environmentObject(_:) 作为该视图的祖先可能会丢失。

我已将环境对象传递给 LoginView() 的所有子视图,但错误仍然存​​在

struct LoginView: View {
    
    @State var loginCredentials = Credentials()
    var loginResponse = LoginResponse()
    var dataCall = DataCall()
    
    var body: some View {
        VStack{
            
            Button(action:{self.dataCall.AttemptLogin(loginCredentials: self.loginCredentials)}){
                
                Text("LOGIN")
                
            }
            
            Text("\(self.loginResponse.jwt)")
            
        }
        .environmentObject(self.loginResponse)
        .padding(.horizontal)
    }
}

如果需要,这是其余的代码

struct Credentials: Encodable {
    var login: String = ""
    var password: String = ""
}

class LoginResponse: Decodable, ObservableObject {
    
    enum CodingKeys: CodingKey {
        case success, userId, jwt
    }
    
    @Published var success: Bool = false
    @Published var userId: String = ""
    var error: String = ""
    @Published var jwt: String = ""
    init(){}
    required init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        success = try values.decode(Bool.self, forKey: .success)
        userId = try values.decode(String.self, forKey: .userId)
        jwt = try values.decode(String.self, forKey: .jwt)
    }
}

struct DataCall {
    
    @EnvironmentObject var dataResponse : LoginResponse
    
    func AttemptLogin(loginCredentials: Credentials)  {
        
        let loginResponse = LoginResponse()
        dataResponse.success = loginResponse.success
        
        }
}
4

1 回答 1

1

由于DataCall不是 SwiftUI 视图,我不相信您可以使用.environmentObject修饰符将数据传递给它。相反,只需LoginResponse在结构中添加对对象的引用DataCall,然后像往常一样通过构造函数传递它。

例子:

struct DataCall {
  weak var dataResponse : LoginResponse
  ...
}

let dataCall = DataCall(dataResponse: loginResponse)

但是,我对您的视图设计感到很困惑。您通常在视图中声明的任何对象,没有@Stateor @ObservedObject,将被一遍又一遍地重新创建。那是你要的吗?

于 2020-08-05T16:01:52.787 回答