【问题标题】:Data not displayed correctly when using addSnapshotListener in Firestore在 Firestore 中使用 addSnapshotListener 时数据未正确显示
【发布时间】:2020-04-29 10:00:20
【问题描述】:

我正在使用addSnapshotListener实时获取数据。

将数据添加到我的 Firestore 数据库时,我得到了一个意外的结果:

func addItem(title: String) {
    self.db.collection("items").document(stage.stageId).setData([
        "title": title,
    ]) { err in
        if let err = err {
            print("Error adding document: \(err)")
        } else {

        }
    }
}

例如,如果项目为空,并且您执行一次addItem (title:" Test "),则ListView 中会显示三个标题为“测试”的数据项。

struct ListView: View {
    @ObservedObject var fetcher = Fetcher()

    var body: some View {
        VStack {
            ForEach(self.fetcher.data.indices, id: \.self) { idx in
                Text(self.fetcher.data[idx].title)
            }
        }
    }
}

class Fetcher: ObservableObject {
    @Published var data: [ItemModel] = []
    private var db: Firestore!

    init() {
        db = Firestore.firestore()
        fetchData()
    }

    private func fetchData() {
        self.db.collection("items").addSnapshotListener { querySnapshot, error in
            if let error = error {
                print("Error getting documents: \(error)")
            }

            guard let documents = querySnapshot?.documents else {
                print("Error fetching documents: \(error!)")
                return
            }

            for document in documents {
                self.data.append(ItemModel(
                    title: document.data()["title"]as! String,
                ))
            }
        }
    }
}

struct ItemModel: Identifiable {
    var id = UUID()
    var title: String
}

上面的代码有问题吗?

谢谢。

【问题讨论】:

  • ItemModel 是否实现了Identifiable?这是必需的,因此ListView 可以区分元素。另外,我想知道您是否通过 Firebase 使用 Firestore。

标签: swift google-cloud-firestore swiftui


【解决方案1】:

前几天我遇到了这个问题。 commentElements 是我的课程,而 cmets 是我发布的变量。我认为 id: .self 是问题,但我不记得了。 (我在 Firebase 上存储了 3 个评论文档,但它只返回了第一个评论 3 次。

List {
            ForEach(commentElements.comments, id: \.comment) { item in
            VStack(spacing: 15) {
                HStack {
                    Text("")
                        .font(.footnote)
                        .fontWeight(.regular)
                        .multilineTextAlignment(.leading)
                    Text("said on \(self.newComment.date.dateValue())")
                        .font(.footnote)
                        .fontWeight(.thin)
                }
                Text(item.comment).font(.footnote).bold()

【讨论】:

    猜你喜欢
    • 2021-06-26
    • 2021-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多