1

我使用新的 @FirestoreQuery 属性包装器,它使用下面的代码。但我需要使用它/用变量初始化它,我该怎么做(见下文我想要做什么)?

import SwiftUI
import FirebaseFirestoreSwift

struct TestFirestoreQuery: View {
    @State var itemLimit: Int = 5
    let increment: Int = 5
    
    @FirestoreQuery(collectionPath: "/discussions/blablabal/messages",
                    predicates: [
                        .order(by: "dateCreated", descending: true),
                        .limit(to: 5)
                    ]
    ) fileprivate var MessageResults: Result<[Message_M], Error>
    
    var body: some View {
        VStack {
            if case let .success(Messages) = MessageResults {
                List(Messages.reversed()) { message in
                    Text("\(message.msg)")
                }
                .refreshable{
                    itemLimit += increment
                    $MessageResults.predicates = [
                        .order(by: "dateCreated", descending: true),
                        .limit(to: itemLimit)
                    ]
                }
            }
            else if case let .failure(error) = MessageResults {
                // Handle error
                Text("Couldn't map data: \(error.localizedDescription)")
            }
            Button {
                itemLimit += increment
                $MessageResults.predicates = [
                    .order(by: "dateCreated", descending: true),
                    .limit(to: itemLimit)
                ]
            } label: {
                Text("Tap me!")
                    .padding()
                    .foregroundColor(.white)
                    .background(.red)
            }
        }
    }
}

我想做但它不起作用:

...
    @State var itemLimit: Int = 5
    let increment: Int = 5
    let path: String = "/discussions/blablabal/messages"
    
    @FirestoreQuery(collectionPath: path,
                    predicates: [
                        .order(by: "dateCreated", descending: true),
                        .limit(to: itemLimit)
                    ]
    ) fileprivate var MessageResults: Result<[Message_M], Error>

...

我收到了这些错误:

  • 不能在属性初始化器中使用实例成员“路径”;属性初始化程序在“self”可用之前运行...

  • 不能在属性初始化程序中使用实例成员“itemLimit”;属性初始化程序在“自我”可用之前运行

4

2 回答 2

0

@FirestoreQuery创建时,路径变量尚不可用。

为什么需要将路径作为单独的变量?直接将 String 传递到 中不是更容易@FirestoreQuery吗?

@FirestoreQuery(collectionPath: "/discussions/blablabal/messages",
                predicates: [
                    .order(by: "dateCreated", descending: true),
                    .limit(to: itemLimit)
                ]

这样您就不必添加 onAppear 修饰符。

于 2022-01-07T11:04:08.737 回答
0

好的,您可以在 onAppear 中初始化它们:

.onAppear {
           $MessageResults.path = path

           $MessageResults.predicates = [
                          .order(by: "dateCreated", descending: true),
                          .limit(to: itemLimit)
                          ]

}
于 2021-11-17T18:21:12.767 回答