SwiftUI - 检索数据后导航查看

SwiftUI - Navigate to view after retrieving data

所以我正在从 FireStore 中检索数据。我正在成功检索数据。当我第一次点击搜索按钮时,正在下载数据并推送新视图。结果,我得到了一个空白视图。但是当我返回时,再次点击搜索,果然我可以看到我的数据被呈现出来。

我如何才能确保首先拥有我正在搜索的数据然后导航到新视图?我使用了 @State 变量等。但似乎没有任何效果。我正在使用 MVVM 方法。

我的视图模型:

class SearchPostsViewModel: ObservableObject {
    var post: [PostModel] = []
 @State var searchCompleted: Bool = false
    func searchPosts(completed: @escaping() -> Void, onError: @escaping(_ errorMessage: String) -> Void) {
            isLoading = true
        API.Post.searchHousesForSale(propertyStatus: propertyStatus, propertyType: propertyType, location: location, noOfBathrooms: noOfBathroomsValue, noOfBedrooms: noOfBedroomsValue, price: Int(price!)) { (post) in
            self.post = post
            print(self.post.count)
            self.isLoading = false
            self.searchCompleted.toggle()
        }
    

    }
    
}

代码确实有效,但有错误:

                    NavigationLink(destination: FilterSearchResults(searchViewModel: self.searchPostsViewModel)
                        .onAppear(perform: {
                            DispatchQueue.main.async {
                                self.createUserRequest()
                            }
                        })
                        )
                      {
                        Text("Search").modifier(UploadButtonModifier())
                    }

您应该查看 @StateObservableObject

的 Apple 文档

https://developer.apple.com/documentation/combine/observableobject

https://developer.apple.com/documentation/swiftui/state

您的问题是在 non-UI class/View.

中使用 @State

如果您从 Apple SwiftUI 教程入手,可能会有所帮助。因此,您了解包装器的不同之处并了解它们之间的联系。

https://developer.apple.com/tutorials/swiftui

此外,当您 post 提出问题时,请确保您的代码可以复制并粘贴到 Xcode as-is 上,以便人们可以对其进行测试。如果其他开发人员可以看到实际发生的情况,您将获得更好的反馈。随着您的进步,将不会那么容易发现问题。

尝试使用以下修改后的视图模型

class SearchPostsViewModel: ObservableObject {
    @Published var post: [PostModel] = []         // << make both published
    @Published var searchCompleted: Bool = false

    func searchPosts(completed: @escaping() -> Void, onError: @escaping(_ errorMessage: String) -> Void) {
            isLoading = true
        API.Post.searchHousesForSale(propertyStatus: propertyStatus, propertyType: propertyType, location: location, noOfBathrooms: noOfBathroomsValue, noOfBedrooms: noOfBedroomsValue, price: Int(price!)) { (post) in
            DispatchQueue.main.async {
               self.post = post           // << update on main queue
               print(self.post.count)
               self.isLoading = false
               self.searchCompleted.toggle()
           }
        }
    }
}