0

我正在从 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,但我不确定我做错了什么。如何用 4 个对象填充列表self.observer.thoughts

4

1 回答 1

1

我的清单确实有问题。添加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)
                }
            }
        }
    }
}
于 2019-11-19T03:09:32.960 回答