【问题标题】:Type 'Void' cannot conform to 'View' | Swift'Void' 类型不能符合 'View' |迅速
【发布时间】:2021-08-13 10:23:56
【问题描述】:

我正在尝试使用我的 firebase 实时数据库中的数据创建一个列表,但我在列表行上收到此错误:

错误:

Type 'Void' cannot conform to 'View' 

我的代码: struct ActiveGoalsView: 查看 {

    @State var goals = ["finish this project"]
    @State var ref = Database.database().reference()
    
    var body: some View {
        NavigationView {
            List {
                
                ref.child("users").child(Auth.auth().currentUser?.uid ?? "noid").child("goals").observeSingleEvent(of: .value) { snapshot in
                    
                    for snap in snapshot.children {
                        Text(snap.child("title").value)
                    }
                }
                
            }.navigationBarHidden(true)
        }
    }
}

struct ActiveGoalsView_Previews: PreviewProvider {
    static var previews: some View {
        ActiveGoalsView()
    }
}

【问题讨论】:

  • 改用ForEach,在body之外做异步工作

标签: ios swift firebase swiftui


【解决方案1】:

您不能在不返回View 的视图层次结构中间使用像observeSingleEvent 这样的命令式代码。正如评论者所建议的那样,您最好将异步代码移到body 之外(我建议使用ObservableObject)。这是一种解决方案(参见内联 cmets):

class ActiveGoalsViewModel : ObservableObject {
    @Published var children : [String] = []
    
    private var ref = Database.database().reference()

    func getChildren() {
        ref.child("users").child(Auth.auth().currentUser?.uid ?? "noid").child("goals").observeSingleEvent(of: .value) { snapshot in
            
            self.children = snapshot.children.map { snap in
                snap.child("title").value //you may need to use ?? "" if this returns an optional
            }
        }
    }
}

struct ActiveGoalsView: View {
    @State var goals = ["finish this project"]
    @StateObject private var viewModel = ActiveGoalsViewModel()

    var body: some View {
        NavigationView {
            List {
                ForEach(viewModel.children, id: \.self) { child in //id: \.self isn't a great solution here -- you'd be better off returning an `Identifiable` object, but I have no knowledge of your data structure
                    Text(child)
                }
            }.navigationBarHidden(true)
        }.onAppear {
            viewModel.getChildren()
        }
    }
}

【讨论】:

    猜你喜欢
    • 2021-11-24
    • 1970-01-01
    • 1970-01-01
    • 2020-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-27
    • 1970-01-01
    相关资源
    最近更新 更多