【问题标题】:Why is my SwiftUI List populating with the same item 4 times instead of all 4 items?为什么我的 SwiftUI 列表填充相同的项目 4 次而不是全部 4 个项目?
【发布时间】:2019-11-19 02:45:19
【问题描述】:

我正在从 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 个对象填充列表?

【问题讨论】:

    标签: ios swift google-cloud-firestore combine swiftui-list


    【解决方案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)
                    }
                }
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-07
      • 2018-02-23
      • 1970-01-01
      • 2021-12-29
      • 2019-02-21
      • 2013-12-29
      • 1970-01-01
      • 2015-10-08
      相关资源
      最近更新 更多