我正在使用 Firestore 读取数据.addSnapshotListener
并将其解析为自定义模型Thought
对于我的 Firestore 集合中的每个文档,我将一个新Thought
对象附加到 a@Published var thoughts
并thoughts
在 a 中迭代List
。
struct Thought: Identifiable {
public var id: String?
public var name: String
public var thought: String
public var color: String
}
class Observer: ObservableObject {
@Published var thoughts = [Thought]()
init(){
self.thoughts.removeAll()
let db = Firestore.firestore()
db.collection("thoughts")
.addSnapshotListener { querySnapshot, error in
guard let documents = querySnapshot?.documents else {
print("Error fetching documents: \(error!)")
return
}
for document in documents {
var thoughtModel = Thought(id: "", name: "", thought: "", color: "")
thoughtModel.name = document.data()["name"] as! String
thoughtModel.thought = document.data()["thought"] as! String
thoughtModel.color = document.data()["color"] as! String
self.thoughts.append(thoughtModel)
}
}
}
}
struct ThoughtsView: View {
@ObservedObject var observer = Observer()
var body: some View {
VStack {
List {
ForEach(self.observer.thoughts, id: \.name) { thought in
ThoughtCard(color: thought.color,
thought: thought.thought,
name: thought.name)
}
}
}
}
}
当我在我的 Firestore 集合中进行更改或添加文档时,所有对象都会附加到我List
的,而不是List
像我期望的那样被更新。换句话说,如果我的 3 项中有 3 项List
,并且我更改了其中一个 Firestore 文档中的值,我最终会在我的 6 项中List
包含原始 3 项和原始 3 项的副本(已修改)。
如何正确更新我的List
?