SwiftUI 使用数据或仅参考 Firestore 文档打开视图 [英] SwiftUI open view with data or only with a reference to Firestore document
问题描述
我需要打开一个名为 PackageDetails
的视图.
I need to open a view called PackageDetails
.
有两种情况可以打开此视图.
There are two cases in which this view could be opened.
1.如果您从包列表中点按特定包.
我有一个包含所有包的数组.所以我要传递这个列表中的特定结构,并打开这个包视图.PackageDetail(package: package)
.我已经拥有所需的所有数据,因此无需额外调用 Firestore 来获取此文档.
I have an array of all the packages. So I'm passing the specific struct from this list and I'm opening this package view.PackageDetail(package: package)
. I already have all the data I need so I do not need to make an extra call to Firestore to fetch this document.
2.可以通过此应用中某个其他视图的链接打开包视图.
在这种情况下,我没有这个特定包的所有详细信息,但我只有对 Firestore 文档的参考.我正在使用此参考在此视图出现时立即进行查询并获取有关此包的详细信息 PackageDetail(package: packageReference)
In this case I do not have all the details of this specific Package but I have just a reference to the Firestore document. I am using this reference to make a query as soon as this view appears and get the details about this Package PackageDetail(package: packageReference)
我这样做的方法是将 Package 声明为可选 @State var package: PackageModel?
和 onAppear 我正在检查 Package 是否为空.
The ways I'm doing this is by declaring Package as an Optional @State var package: PackageModel?
and onAppear I'm checking if the Package is null or not.
.onAppear {
if let package = self.package {
// package data exists
} else {
// fetch it from firestore
}
}
问题是:我这样做对吗?这是最好的方法吗?
The question is: Am I doing this right? Is this the best approach?
推荐答案
Package
不是视图状态,所以 @State
设计不适合这里.相反,最好使用视图模型模式,因此方法(草率)可能如下所示:
The Package
is not view state, so @State
, by design does not fit here. Instead it is preferable to use view model pattern, so the approach (scratchy) might be like below:
class PackageViewModel: ObservableObject {
@Published var packageReference: URL?
@Published var package: PackageModel?
init(package: PackageModel? = nil, reference: URL? = nil) {
self.package = package
self.packageReference = reference
}
private func loadPackage() {
// do load here from 'self.packageReference' and in callback assign package created from result
DispatchQueue.main.async {
self.package = package
}
}
}
struct PackageView: View {
@ObservedObject var vm: PackageViewModel
var body: some View {
VStack {
// some main part here
if vm.package != nil {
PackageDetail(package: self.vm.package)
}
}
.onAppear {
if self.vm.package == nil {
self.vm.loadPackage()
}
}
}
}
这篇关于SwiftUI 使用数据或仅参考 Firestore 文档打开视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!