简体   繁体   English

Class 或视图未更新

[英]Class or View isn't updating

Basically, I have a class which fetches profile info from Firestore, but when I edit the profile and submit the changes and return to the profile view, the information isn't updated, but it is updated within Firestone, so I have to close the app and relaunch it for it to update within the app.基本上,我有一个 class 从 Firestore 获取配置文件信息,但是当我编辑配置文件并提交更改并返回到配置文件视图时,信息没有更新,但它在 Firestone 中更新,所以我必须关闭应用程序并重新启动它以在应用程序内更新。 I'm assuming my issue is because I am not recalling the class or the view isn't being updated?我假设我的问题是因为我没有回忆起 class 或视图没有更新? Here is my code for the profile view, and the class I call to fetch the data from Firestore.这是我的个人资料视图代码,以及我调用以从 Firestore 获取数据的 class。

ProfileView.swift ProfileView.swift

import SwiftUI
import FirebaseAuth
import FirebaseFirestore


struct ProfileView: View {
    let auth = Auth.auth()
    @ObservedObject private var user = MainUserDataModel() //pulls user data from firebase (located in fetchUserData.swift) works like: user.currentUser?.uid ?? ""
    @State private var firstName = ""
    @State private var lastName = ""
    @State private var email = ""
    
    var body: some View {
        VStack {
            Image("img")
                .resizable()
                .frame(width: 100, height: 100)
                .clipShape(Circle())
                .padding()
            Text("\(firstName) \(lastName)")
                .fontWeight(.bold)
        
            Text("\(email)")
                .font(.caption)
                .padding(5)
            NavigationLink("Edit Profile", destination: EditProfile())
                .foregroundColor(Color.pink)
            Form {
            
            }
            
        }
        .task {
            firstName = user.currentUser?.firstName ?? ""
            lastName = user.currentUser?.lastName ?? ""
            email = user.currentUser?.email ?? ""
            
        }
        //.navigationTitle("Profile")
    }
}


struct ProfileView_Previews: PreviewProvider {
    static var previews: some View {
        ProfileView()
    }
}

fetchUserData.swift fetchUserData.swift

import Foundation
import FirebaseAuth
import Firebase
import FirebaseFirestore

struct User {
    let firstName, lastName, uid, email: String
    
}

class MainUserDataModel: ObservableObject {
    @Published var errorMessage = ""
    @Published var currentUser: User?

    init() {
        fetchUserData()
    }

    private func fetchUserData() {
        let auth = Auth.auth()
        guard let uid = auth.currentUser?.uid else { return }

        Firestore.firestore().collection("users").document(uid).getDocument { snapshot, error in
            if let error = error {
                self.errorMessage = "Failed to fetch current user: \(error)"
                print("Failed to fetch current user:", error)
                return
            }

            guard let data = snapshot?.data() else {
                self.errorMessage = "No data found"
                return

            }
            let firstName = data["firstName"] as? String ?? ""
            let lastName = data["lastName"] as? String ?? ""
            let uid = data["uid"] as? String ?? ""
            let email = data["email"] as? String ?? ""
            self.currentUser = User(firstName: firstName, lastName: lastName, uid: uid, email: email)
        }
    }

}

You're setting your @State variables before the fetchUserData has completed.您在fetchUserData完成之前设置您的@State变量。 It would be cleaner to remove the @State variables altogether and just rely on the @Published values from your MainUserDataModel :完全删除@State变量并仅依赖 MainUserDataModel 中的@Published值会更MainUserDataModel

struct ProfileView: View {
    let auth = Auth.auth()
    @ObservedObject private var user = MainUserDataModel()
    
    var body: some View {
        VStack {
            Image("mank")
                .resizable()
                .frame(width: 100, height: 100)
                .clipShape(Circle())
                .padding()
            if let currentUser = user.currentUser {
                Text("\(currentUser.firstName) \(currentUser.lastName)")
                  .fontWeight(.bold)
                Text("\(currentUser.email)")
                  .font(.caption)
                  .padding(5)
                NavigationLink("Edit Profile", destination: EditProfile())
                .foregroundColor(Color.pink)
            } else {
               //Display a loading indicator
            }
        }
    }
}

You could also use your previous strategy of providing default values:您还可以使用以前提供默认值的策略:

struct ProfileView: View {
    let auth = Auth.auth()
    @ObservedObject private var user = MainUserDataModel()
    
    var body: some View {
        VStack {
            Image("mank")
                .resizable()
                .frame(width: 100, height: 100)
                .clipShape(Circle())
                .padding()
            Text("\(user.currentUser?.firstName ?? "") \(user.currentUser?.lastName ?? "")")
                  .fontWeight(.bold)
            Text("\(user.currentUser?.email ?? "")")
                  .font(.caption)
                  .padding(5)
            NavigationLink("Edit Profile", destination: EditProfile())
                .foregroundColor(Color.pink)
        }
    }
}

If instead, you really need the @State variables, you shouldn't set them until your MainUserDataModel loads the data -- you can use onReceive and watch for changes to the currentUser publisher.相反,如果您确实需要@State变量,则不应在MainUserDataModel加载数据之前设置它们——您可以使用onReceive并观察对currentUser发布者的更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 运算符“[]”未为 class“对象”定义。 flutter - The operator '[]' isn't defined for the class 'Object'. flutter 未为 class“FirebaseAuth”2 定义方法“signInWithGoogle” - The method 'signInWithGoogle' isn't defined for the class 'FirebaseAuth' 2 没有为 class 'AppJsImpl' 定义方法 'delete' - The method 'delete' isn't defined for the class 'AppJsImpl' Flutter:没有为 class '对象'定义 getter 'userId' - Flutter: The getter 'userId' isn't defined for the class 'Object' 错误:没有为 class 'FirebaseCoreWeb' 定义 getter 'completercd' - Error: The getter 'completercd' isn't defined for the class 'FirebaseCoreWeb' FlutterError:没有为 class '_PinputState' 定义方法 'FocusTrapArea' - FlutterError: The method 'FocusTrapArea' isn't defined for the class '_PinputState' :错误:没有为 class 'FirebaseAuth' 定义 getter 'gmrethrow' - : Error: The getter 'gmrethrow' isn't defined for the class 'FirebaseAuth' 错误:未为 class“地理定位器”定义方法“getPositionStream” - Error: The method 'getPositionStream' isn't defined for the class 'Geolocator' 错误:没有为 class 'Future 定义 getter 'uid'<firebaseuser> 功能()'</firebaseuser> - Error: The getter 'uid' isn't defined for the class 'Future<FirebaseUser> Function()' 错误:没有为 class 'Object' 定义 getter 'documents' - Error: The getter 'documents' isn't defined for the class 'Object'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM