谁能帮我解决这个问题?
.navigationDestination(for: User.self, destination: { user in
let chat = Task { try await viewModel.createChat(currentUserId: currentUser!.id, opposingUserId: user.id) }
if chat == ChatModel.self {
ChatView(chat: chat)
} else {
Text("Fehler: Chat konnte nicht erstellt oder gefunden werden")
}
})
我基本上想做的是将异步函数 createChat 的 returnValue (如果不抛出错误,它应该返回 ChatModel)分配给我的聊天常量。然后我试图查明任务是否返回 ChatModel 还是错误。如果它返回 ChatModel,则应使用 chatModel 初始化 ChatView,否则现在应显示文本。
编辑:它应该适用于此:
这是否适用于这样的结构:
var body: some View {
NavigationStack {
ScrollView {
LazyVStack {
ForEach(viewModel.users) { user in
NavigationLink(value: user) {
VStack {
UserCell(user: user, buttonText: "startChat")
Divider()
}
.padding(.vertical, 4)
}
}
}
}
.navigationDestination(for: User.self) { user in ChatView(user: user) }
}
}
这种 SwiftUI 导航形式的
destination
确实应该尽可能简单明了 View
。
我会考虑有一个接受
User
对象的外部聊天视图。它可以有一个 @State 来表示聊天的加载状态;您将根据 Task
更新状态,并根据加载状态选择哪个子视图。例如(这是非常粗糙的代码):
enum LoadingState {
case loading
case loaded(ChatModel)
case error(Error)
}
struct ChatView: View {
var user: User
@State private var loadingState: LoadingState = .loading
var body: some View {
Group { // because you can't attach modifiers directly to a switch
switch loadingState {
case .loading:
Text("Loading...")
case .loaded(let chatModel):
ChatModelView(model: chatModel)
case .error(let error):
Text(error.localizedDescription)
}
}
.task {
do {
let chatModel = try await viewModel.createChat(currentUserId: currentUser!.id, opposingUserId: user.id)
loadingState = .loaded(chatModel)
catch {
loadingState = .error(error)
}
}
}
}
然后父视图中的设置将是
.navigationDestination(for: User.self) { user in ChatView(user: user) }