为什么我的SwiftUI列表会用同一个项目填充4次,而不是全部4个项目



我正在从Firestore读取数据,并将其解析为自定义模型Thought

对于Firestore集合中的每个文档,我都会将一个新的Thought对象附加到@Published var thoughts中。

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(){
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)
}
print(self.thoughts) //PRINTS 4 DIFFERENT THOUGHT OBJECTS
}
}
}
struct ThoughtsView: View {
@ObservedObject var observer = Observer()
var body: some View {
VStack {
List {
ForEach(self.observer.thoughts) { thought in
ThoughtCard(color: thought.color,
thought: thought.thought,
name: thought.name)
//HERE I GET THE SAME CARD 4 TIMES INSTEAD OF 4 DIFFERENT CARDS
}
}
}
}
}

当我打印thoughts时,我会看到Firestore数据库中当前的所有4个文档。然而,当我尝试在列表中的thoughts中迭代时,我只对同一个Thought对象进行了4次迭代,而不是4个不同的Thought对象。

我认为问题在于List以及我如何迭代self.observer.thoughts,但我不确定我做错了什么。如何用self.observer.thoughts中的4个对象填充列表?

我的List确实有问题。添加id:参数后,List似乎能够识别每个Thought对象并相应地显示它们。

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)
}
}
}
}
}

相关内容

  • 没有找到相关文章

最新更新