我的应用程序中存在更新问题。 我不太了解子视图之间的数据流是怎么回事。
ViewModel :ObsebsrvableObject
MainView 和ObservedObject(viewModel)
每次修改列表时,MainView更新都会触发ChildView的新重建,但NephewView不会更新
每次观察对象更新时,我想更新Main,Child和NephewView视图。
我不明白为什么重建子视图时,侄子不重建。
class ViewModel: ObservableObject {
let userData = UserData.shared
var canceller: AnyCancellable?
@Published var items: [Items]
init() {
items = []
canceller = userData.objectWillChange
.throttle(for: 5, scheduler: RunLoop.main, latest: true)
.sink(receiveCompletion: { data in
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
self.items = data.items
}
},
receiveValue: { _ in
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
self.items = data.items
}
})
}
}
struct MainView: View {
@ObservedObject var model = ViewModel()
var body: some View {
ChildView(items: model.items)
}
}
struct ChildView: View {
let items: [Items]
var body: some View {
NephewView(items: items)
}
}
struct NephewView: View {
let items: [Items]
var body: some View {
List...
}
}
接收器正常工作,只是UI部分没有更新。 也许我更新发布者的方式是错误的?
答案 0 :(得分:0)
您的MainView
ChildView(items: $model.items)
您的ChildView
struct ChildView: View {
@Binding let items: [Items]
var body: some View {
List {
ForEach(self.items) { item in
NephewView(items: item)
}
}
}
}
您的NephewView
struct NephewView: View {
@Binding let items: item
var body: some View {
// Your view logic goes here with single item
}
}