You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI评论功能:数据打印正常但视图不显示问题排查

问题分析与解决方案

核心问题

你的CommentsViewModel中,getComments方法仅通过completion回调返回了评论数据,但没有将数据赋值给@Published修饰的comments数组。SwiftUI依赖@Published属性的变化触发视图更新,数组始终为空的情况下,ForEach自然不会渲染任何内容。


具体修复步骤

1. 修改getComments方法,直接更新@Published属性

移除不必要的completion回调,在获取到评论数据后,将其赋值给self.comments,并且切换到主线程执行(Firestore回调默认在后台线程,UI更新必须在主线程):

func getComments(id: String) {
    Firestore.firestore().collection("posts").document(id).collection("comments")
        .order(by: "timestamp", descending: true)
        .getDocuments { snapshot, error in
            guard let documents = snapshot?.documents else {
                DispatchQueue.main.async {
                    self.noComments = true
                }
                return
            }
            let comments = documents.compactMap({ try? $0.data(as: Comment.self) })
            DispatchQueue.main.async {
                self.comments = comments
                self.noComments = comments.isEmpty
            }
        }
}

2. 调整post属性的didSet逻辑

因为已经不需要completion回调,直接调用无参数的getComments方法即可:

var post: Post? {
    didSet {
        if let postId = post?.id {
            getComments(id: postId)
        }
    }
}

3. 确保Comment模型支持ForLoop渲染

检查你的Comment结构体是否遵循Identifiable协议(如果已有id属性,只需添加协议遵循):

struct Comment: Identifiable, Codable {
    var id: String
    // 其他属性(如内容、时间戳、用户ID等)
}

如果不想遵循Identifiable,也可以在ForEach中显式指定id:

ForEach(commentsData.comments, id: \.id) { comment in
    CommentsRow(post: post, comment: comment, commentData: commentsData)
}

修复后验证

当CommentsView的onAppear设置commentsData.post = post时,会触发post的didSet方法,调用getComments获取数据并更新comments数组。SwiftUI会感知到@Published属性的变化,自动刷新视图渲染评论列表。

内容的提问来源于stack exchange,提问作者robowarrior

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 04:10:15