gpt4 book ai didi

SwiftUI 不会更新第二个 NavigationLink 目的地

转载 作者:行者123 更新时间:2023-12-03 17:00:48 30 4
gpt4 key购买 nike

我有一个列表,其中包含推送 View 的行。该 View 有另一个列表,它推送另一个 View 。原来的List,第一个推送的List会随着数据的变化而更新。但是,推送时最后一个 View 不会更新。当我向后滑动 View 不再更新时,即使它曾经更新过。

HomeView > UserView > ItemView

User 和 Item 是可识别的结构。我试过让它们 Hashable 并使用 id: \.self ,但这似乎也不起作用。

class App: ObservableObject {
@Published var users = [User]()
}

struct HomeView {

@EnvironmentObject var app: App

var body {
List {
Section {
ForEach(app.users) { user in
NavigationLink(destination: UserView(user: user)) {
Text(user.name)
}
}
}
}
}

}

// Updates fine when `app.users` updates
// Stops updating after going back from ItemView
struct UserView {

let user: User

var body {
List {
Section {
ForEach(user.items) { item in
NavigationLink(destination: ItemView(user: user, item: item)) {
Text(item.name)
}
}
}
}
}

}

/// Does not update when app.users updates
struct ItemView {

let user: User
let item: Item

var body {
List {
Section {
ForEach(item.details) { detail in
Text(detail)
}
}
}
}

}

最佳答案

这是我所做的测试并且运行良好,一切都按预期更新。

struct User: Identifiable {
var id: String
var name: String
var items: [Item]
}

struct Item: Identifiable {
var id: String
var name: String
var details: [String]
}

class App: ObservableObject {
@Published var users = [User]()

init() {
let items1 = [Item(id: UUID().uuidString, name: "item1", details: ["d1","d2"]), Item(id: UUID().uuidString, name: "item2", details: ["d3","d4"])]
let items2 = [Item(id: UUID().uuidString, name: "item3", details: ["e1","e2"]), Item(id: UUID().uuidString, name: "item4", details: ["e3","e4"])]
users.append(User(id: UUID().uuidString, name: "user1", items: items1))
users.append(User(id: UUID().uuidString, name: "user2", items: items2))
}
}


struct ContentView: View {

@ObservedObject var app = App()

var body: some View {
NavigationView {
List {
ForEach(app.users) { user in
NavigationLink(destination: UserView(user: user)) {
Text(user.name)
}
}
}
}
}
}


struct UserView: View {
@State var user: User

var body: some View {
List {
ForEach(user.items) { item in
NavigationLink(destination: ItemView(item: item)) {
Text(item.name)
}
}
}
}
}

struct ItemView: View {
@State var item: Item

var body: some View {
List {
ForEach(item.details, id: \.self) { detail in
Text(detail)
}
}
}
}

关于SwiftUI 不会更新第二个 NavigationLink 目的地,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61074131/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com